第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React 可選擇性的使用自有 state 或者 props 元件

React 可選擇性的使用自有 state 或者 props 元件

慕勒3428872 2019-05-12 09:29:05
我想做一個如果有props有value傳入,就使用props的value,沒有傳入的話,就使用自有狀態(tài)的元件代碼如下DEMO:https://stackblitz.com/edit/r...importReactfrom'react';exportdefaultclassMyInputextendsReact.Component{constructor(props){super(props);this.state={value:(typeofthis.props.value==='string')?this.props.value:''}}componentWillReceiveProps(nextProps){if((typeofthis.props.value==='string')?this.props.value:''){this.setState({value:nextProps.value})}}handleChange=(e)=>{if(this.props.onChange){this.props.onChange(e);}else{this.setState({value:e.target.value});}}handleClick=(e)=>{if(this.props.onClick){this.props.onClick(e);}else{}}render(){return}}但我認為這樣的代碼有點冗長,似乎考慮不周,請問有沒有這種元件的比較好的寫法可以推薦呢?
查看完整描述

2 回答

?
慕絲7291255

TA貢獻1859條經(jīng)驗 獲得超6個贊

首先,不要在constructor()方法中,使用this.props,這個寫法在IE下無法兼容。
其次,componentWillReceiveProps()方法,將會廢棄。
可以做如下的修改:
render(){
const{value=this.state.value}=this.props;
return
}
你的需求是項目中最常見的使用方式:
importReactfrom'react';
exportdefaultclassMyInputextendsReact.Component{
constructor(props){
super(props);
this.state={value:''};
}
handleChange=(e)=>{
if(this.props.onChange){
this.props.onChange(e);
}else{
this.setState({value:e.target.value});
}
}
handleClick=(e)=>{
if(this.props.onClick){
this.props.onClick(e);
}else{
}
}
render(){
const{value=this.state.value}=this.props;
return
}
}
                            
查看完整回答
反對 回復 2019-05-12
  • 2 回答
  • 0 關注
  • 448 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號