onChange 方法将触发 state 的更新并将更新的值传递到子组件的输入框的 value 上来重新渲染界面

2017-07-17 18:04:00
admin
原创
539
<!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>
            <input type="text" value={this.props.myDataProp} onChange={this.props.updateStateProp} /> 
            <h4>{this.props.myDataProp}</h4>
            </div>;
  }
});
var HelloMessage = React.createClass({
  getInitialState: function() {
    return {value: 'Hello ybao.org!'};
  },
  handleChange: function(event) {
    this.setState({value: event.target.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
  • 公众号:源宝网络