问题导向
受控组件与非受控组件是什么?如何使用?
如果你都有了答案,可以忽略本文章,或去react学习地图寻找更多答案
受控组件
- 组件的变化受到this.setState的影响
- 自身有state
- 没有自己的state,所有的数据都来自props
非受控组件
- 组件的变化不会受到this.setState的影响,而是来自ref
- 必须操作DOM时,setState实现不了,如文件上传,富文本编辑器
- 可以调用子组件的方法,但子组件必须是类组件才可以
注意
使用非受控组件时
input使用defaultValue替代value
checkbox使用defaultChecked替代Checked
例子
受控组件
input的value受到this.setState的影响,会改变
import React,{PrueComponet} from 'react'
class Hello extends PrueComponet {
constructor(props){
super(props)
this.state = {
inputValue = ''
}
}
componetDidMount(){
this.setState({
inputvalue: 'hello react'
})
}
changeInputValue(e){
this.setState({
inputvalue:e.target.value
})
}
render(){
return (
<div>
<p>{this.state.inputValue}</p>
<input
value={this.state.inputValue}
onchange={() => this.changeInputValue()}
/>
</div>
)
}
}
非受控组件
input已经变为非受控组件,this.setState不会改变input中的值
import React, { Component } from 'react'
class Hello extends Component {
constructor() {
super()
this.state = {
inputValue: 'hello world'
}
this.inputRef = React.createRef()
}
alertInputValue() {
const input = this.inputRef.current
this.setState({
inputValue: 'xxx'
})
alert(input.value)
}
render() {
return (
<div>
<p>{this.state.inputValue}</p>
<input
defaultValue={this.state.inputValue}
ref={this.inputRef}
/>
<button onClick={() => this.alertInputValue()}>alert inputValue</button>
</div>
)
}
}
export default Hello;
调用子组件方法
import React, { useCallback, useRef } from 'react'
import Test from './component/hook/Test'
function App() {
const testRef = useRef()
const click = useCallback(() => {
testRef.current.sayHi()
}, [])
return (
<div className="App">
<Test ref={testRef} />
</div>
)
}
export default App
实际应用场景:图片上传
import React, { Component } from 'react'
class Hello extends Component {
constructor(props) {
super(props)
this.fileUploadRef = React.createRef()
}
alertFileName() {
const ele = this.fileUploadRef.current
alert(ele.files[0].name)
}
render() {
return (
<div>
<input
type="file"
ref={this.fileUploadRef}
/>
<button onClick={() => this.alertFileName()}>alert fileName</button>
</div>
)
}
}
export default Hello;
学习更多