React組件通信(父傳子,子傳父) - 前端

父組件向子組件傳值(通過props傳值)

子組件:

class Children extends Component{
  constructor(props){
    super(props);
  }
  render(){
    return(
      <div>這是:{this.props.name}</div> // 這是 父向子
    )
  }
}

父組件:

class App extends React.Component{
  render(){
    return(
      <div>
        <Children name="父向子"/>
      </div>
    )
  }
}

父組件向子組件傳值(回調函數)

子組件:

class Children extends Component{
  constructor(props){
    super(props);
  }
  handerClick(){
    this.props.changeColor('skyblue') // 執行父組件的changeColor 並傳參 必須和父組件中的函數一模一樣
  }
  render(){
    return(
      <div>
        <div>父組件的背景色{this.props.bgcolor}</div> // 子組件接收父組件傳過來的值 bgcolor
        <button onClick={(e)=>{this.handerClick(e)}}>改變父組件背景</button> // 子組件執行函數
      </div>
    )
  }
}

父組件:

class Father extends Component{
  constructor(props){
    super(props)
    this.state = {
      bgcolor:'pink'
    }
  }
  bgChange(color){
    this.setState({
      bgcolor:color
    })
  }
  render(props){
    <div style={{background:this.state.bgcolor}}>
            // 給子組件傳遞的值 color 
      <Children bgcolor={this.state.bgcolor} changeColor={(color)=>{this.bgChange(color)}} /> 
                        // changeColor 子組件的參數=color 當做形參
    </div>
  }
}

子組件向父組件傳值

子組件:
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.bind(this)}/>
            </div>
        )
    }
});
React.render(
  <Parent />,
  document.getElementById('test')
);

原文章:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章