其他分享
首页 > 其他分享> > react 之 父子组件传值(看后即懂)

react 之 父子组件传值(看后即懂)

作者:互联网

父组件

class Data_Reconciliation extends Component {
    constructor(props) {
        super(props)
        this.state = {
       		btnName: '点击',
            radioValue: 'youyong', // 单选框的值
        }
    }
    changeText = (value) => {
        this.setState({ radioValue: value })
    }
    render() {
        return (
            <div className="data-reconciliation">
                <p>{this.state.radioValue}</p>
                <ListItem btnName={this.state.btnName}  pfn={this.changeText}></ListItem>
            </div>
        )
    }
}

子组件

class ListItem extends Component {
    constructor(props) {
        super(props)
    }
    handerClick = () => {
        this.props.pfn('涛哥')
    }
    render() {
        return (
            <button onClick={this.handerClick}>{this.props.btnName}</button>
        )
    }
}

父传子:

父组件直接在子组件上面添加需要传递的属性,本例传的是btnName,然后子组件通过this.props.btnName就可以拿到值

子传父:

父组件先定义一个获取值的方法,然后子组件触发父组件的这个方法,通过传参进行传值,本例是父组件定义changeText 方法,然后把方法传给子组件,子组件再触发父组件的方法,传递数据过去

是不是很简单啊

标签:看后,本例,react,传值,props,组件,radioValue,方法,btnName
来源: https://blog.51cto.com/u_14846736/2742761