react中的受控元件,非受控元件;
阿新 • • 發佈:2019-02-18
剛開始react的時候就接觸到受控元件和非受控元件這個概念,然後那個時候長用的元件,比如input,select都是屬於受控元件。
受控元件:
<input
type="text"
value={this.state.value}
onChange={(e) => {
this.setState({
value: e.target.value,
});
}}
/>
<input>
要繫結一個onChange事件,每當輸入資訊時,onChange方法監聽到資訊,這時候需要把資訊通過setValue的方式寫入到state中,然後state改變觸發render的再次渲染,然後把state的值傳輸到input元件中,input元件中的value就是接收這個傳輸值,然後再顯示出來。這也是react元件的一個狀態控制原理。
非受控元件:
顧名思義,就是不受state的狀態值改變而改變,只是具有一個類似於defaultValue這樣的初始值來設定狀態,或者說只接受props的改變而改變的元件,自身不會去改變state的值。
遇到過的坑:
antd的Upload的元件當添加了fileList屬性後,變成了一個主動控制的受控元件,在onChang中需要始終setState fileList,保證所有的狀態同步到Upload內。
程式碼如下:
<Upload
name='file'
action={`/api/v1/special-train/wenyanyuanwen-voice?wenyanyuanwenId=${wenyanyuanwenId}&voiceId=${voiceData && voiceData.id || null}`}
data={this.upLoadData}
fileList={this.state.audioFileList}
beforeUpload={this.audioBeforeUpload}
onChange={this.audioOnChange}
>
{!audioShow
? <Button>
<Icon type="upload" /> Click to Upload
</Button>
: null
}
</Upload>
audioOnChange = (info) => { const status = info.file.status; console.log("上傳音訊info====", info); if (this.state.audioShowUploadList) { console.log("上傳音訊info.fileList====", info); this.setState({ audioFileList: info.fileList }); } if (status !== 'uploading') { console.log(info.file, info.fileList); } if (status === 'done') { message.success(`${info.file.name} file uploaded successfully.`); this.setState({ audioShow: true }); } else if (status === 'error') { message.error(`${info.file.name} file upload failed.`); } }