从子组件中更新父组件的 state 时,你需要在父组件通过创建事件句柄 (handleChange) ,并作为 prop (updateStateProp) 传递到你的子组件上

2017-07-17 18:10:00
admin
原创
629
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>React 实例</title>
    <script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
	<script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
	<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
    var Content = React.createClass({
      render: function() {
        return  <div>
                  <button onClick = {this.props.updateStateProp}>点我</button>
                  <h4>{this.props.myDataProp}</h4>
               </div>
      }
    });
    var HelloMessage = React.createClass({
      getInitialState: function() {
        return {value: 'Hello ybao.org!'};
      },
      handleChange: function(event) {
        this.setState({value: '教程'})
      },
      render: function() {
        var value = this.state.value;
        return <div>
                <Content myDataProp = {value} 
                  updateStateProp = {this.handleChange}></Content>
               </div>;
      }
    });
    ReactDOM.render(
      <HelloMessage />,
      document.getElementById('example')
    );
    </script>
  </body>
</html>
  • QQ讨论群
  • 关注微信
    • 欢迎咨询
    • 欢迎加入QQ群 16506021
  • 公众号:源宝网络