zoukankan      html  css  js  c++  java
  • React子组件与父组件传值

    一 子组件向父组件传值

    //子组件
    var Child = React.createClass({
    render: function(){
    return (
    <div>
    请输入邮箱:<input onChange={this.props.handleEmail}/>
    </div>
    )
    }
    });
    //父组件,此处通过event.target.value获取子组件的值
    var Parent = React.createClass({
    getInitialState: function(){
    return {
    email: ''
    }
    },
    handleEmail: function(event){
    this.setState({email: event.target.value});
    },
    render: function(){
    return (
    <div>
    <div>用户邮箱:{this.state.email}</div>
    <Child name="email" handleEmail={this.handleEmail}/>
    </div>
    )
    }
    });
    React.render(
    <Parent />,
    document.getElementById('test')
    );

    2 常用

    //子组件,handleVal函数处理用户输入的字符,再传给父组件的handelEmail函数
    var Child = React.createClass({
    handleVal: function() {
    var val = this.refs.emailDom.value;
    val = val.replace(/[^0-9|a-z|@|.]/ig,"");
    this.props.handleEmail(val);
    },
    render: function(){
    return (
    <div>
    请输入邮箱:<input ref="emailDom" onChange={this.handleVal}/>
    </div>
    )
    }
    });
    //父组件,通过handleEmail接受到的参数,即子组件的值
    var Parent = React.createClass({
    getInitialState: function(){
    return {
    email: ''
    }
    },
    handleEmail: function(val){
    this.setState({email: val});
    },
    render: function(){
    return (
    <div>
    <div>用户邮箱:{this.state.email}</div>
    <Child name="email" handleEmail={this.handleEmail}/>
    </div>
    )
    }
    });
    React.render(
    <Parent />,
    document.getElementById('test')
    );

    二 父组件向子组件传值

    State 和 Props

    以下实例演示了如何在应用中组合使用 state 和 props 。我们可以在父组件中设置 state, 并通过在子组件上使用 props 将其传递到子组件上。在 render 函数中, 我们设置 name 和 site 来获取父组件传递过来的数据。

    var WebSite = React.createClass({
      getInitialState: function() {
        return {
          name: "菜鸟教程",
          site: "http://www.runoob.com"
        };
      },
     
      render: function() {
        return (
          <div>
            <Name name={this.state.name} />
            <Link site={this.state.site} />
          </div>
        );
      }
    });
    
    var Name = React.createClass({
      render: function() {
        return (
          <h1>{this.props.name}</h1>
        );
      }
    });
    
    var Link = React.createClass({
      render: function() {
        return (
          <a href={this.props.site}>
            {this.props.site}
          </a>
        );
      }
    });
    
    React.render(
      <WebSite />,
      document.getElementById('example')
    );
  • 相关阅读:
    给大家分享两款正在使用的reflector插件
    Win32汇编项目总结——猎杀潜航
    SQL Server2008 数据库误删除数据的恢复方法分享
    DataGridView中使DataGridViewComboBox可编辑
    将SQL数据库还原到某个时间点
    SQL Server 2005对海量数据处理
    SQL Server 2005对海量数据处理(1)
    ILDASM的使用
    QT简介以及配置
    Reflector插件介绍
  • 原文地址:https://www.cnblogs.com/cxf520/p/5913464.html
Copyright © 2011-2022 走看看