zoukankan      html  css  js  c++  java
  • react 之props传值

    props 可以把数据从父传给子,如果想要实现子传给父数据,可以把数据当成函数的参数传递给父组件,下面给一行代码揣摩:

    class ParentCom extends React.Component{
        constructor(props){
            super(props)
            this.state = {
                childData:null
            }
        }
        render(){
            return (
                <div>
                    <h1>子元素传递过来的数据:{this.state.childData}</h1>
                    <ChildCom setChildData={this.setChildData}/>
                </div>
            )
        }
        setChildData = (data) => {
            this.setState({
                childData:data
            })
        }
    }

    class ChildCom extends React.Component{
        constructor(props){
            super(props)
            this.state = {
                msg: "helloworld"
            }
        }
        render(){
            return (
                <div>
                    <button onClick={this.sendData}>传递helloword给父元素</button>
                </div>
            )
        }
        sendData = () => {
            this.props.setChildData(this.state.msg)
        }
    }

    ReactDOM.render(
        <ParentCom/>,
        document.getElementById('root')
    )
  • 相关阅读:
    对称的二元变量和不对称的二元变量之间的区别是什么?
    数据挖掘中ID3算法实现zz
    深入浅出谈数据挖掘zz
    JS动态生成表格后 合并单元格
    JS 点击元素发ajax请求 打开一个新窗口
    JS实现拖动div层移动
    简单的表格json控件
    JS添加标签效果
    JS模板引擎
    如何使用seajs+jQuery构建中型项目
  • 原文地址:https://www.cnblogs.com/xu3241/p/13823119.html
Copyright © 2011-2022 走看看