React:props、ref(父子间通信)

react父子组件间通信:除了用props外,还可以用父组件调用子组件的ref写的方法,得到子组件的实例。可以获取子组件全部信息,包括状态和方法:

Refs and the DOM Refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素。

在典型的 React 数据流中,props 是父组件与子组件交互的唯一方式。要修改一个子组件,你需要使用新的 props 来重新渲染它。但是,在某些情况下,你需要在典型数据流之外强制修改子组件。被修改的子组件可能是一个 React 组件的实例,也可能是一个 DOM 元素。对于这两种情况,React 都提供了解决办法。

React 中ref的几种用法 1.字符串 通过 this.refs.a 来引用真实dom的节点 dom 节点上使用

<input  type ="text" ref="a"/>

1 2.回调函数 回调函数就是在dom节点或组件上挂载函数,函数的入参是dom节点或组件实例,达到的效果与字符串形式是一样的, 都是获取其引用。

<input type="text" ref={(input)=>{this.textInput=input}}

1 3.React.createRef() 在React 16.3版本后,使用此方法来创建ref。将其赋值给一个变量,通过ref挂载在dom节点或组件上,该ref的current属性将能拿到dom节点或组件的实例

class Counter extends Component {
    constructor() {
        super()
        this.state ={sum:0,number:0}
        this.myRef = React.createRef();
    }
    change = () =>{
        this.setState({...this.state,sum: Number(this.textInput.value) + Number(this.myRef.current.value)})
    }
    componentDidMount(){
        console.log(this.myRef.current.value);
    }
    render() {
        return (
            <div onChange ={this.change} >
                <input type="text" ref={(input)=>{this.textInput=input}} />+ 
                <input  type ="text" ref={this.myRef} /> = {this.state.sum}
            </div>
            
        )
    }
}

用于组件间的通信:

// 父组件
class Parent extends React.Component {
testRef=(ref)=>{
this.child = ref
console.log(ref) // -> 获取整个Child元素
}
handleClick=()=>{
alert(this.child.state.info) // -> 通过this.child可以拿到child所有状态和方法
}
render() {
return <div>
<Child onRef={this.testRef} />
<button onClick={this.handleClick}>父组件按钮</button>
</div>
}
// 子组件
class Child extends React.Component {
constructor(props) {
super(props)
this.state = {
info:快点击子组件按钮哈哈哈
}
}
componentDidMount(){
this.props.onRef(this)
console.log(this) // ->将child传递给this.props.onRef()方法
}
handleChildClick=()=>{
this.setState({info:通过父组件按钮获取到子组件信息啦啦啦})
} 
render(){
return <button onClick={this.handleChildClick}>子组件按钮</button>
}
}

当在子组件中调用onRef函数时,正在调用从父组件传递的函数。this.props.onRef(this)这里的参数指向子组件本身,父组件接收该引用作为第一个参数:onRef = {ref =>(this.child = ref)}然后它使用this.child保存引用。之后,可以在父组件内访问整个子组件实例,并且可以调用子组件函数。

参考:https://blog..net/weixin_44058725/article/details/100928623 https://blog..net/zhang_xin_new/article/details/91458022?ops_request_misc=&request_id=&biz_id=102&utm_term=react%20:ref&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-0-91458022.first_rank_v2_pc_rank_v29&spm=1018.2226.3001.4187

经验分享 程序员 微信小程序 职场和发展