react均是以組件構成,那父子組件傳值就很重要了
父組件傳值給子組件,不僅可以傳值,傳事件,還可以傳實例
1、父組件傳值給子組件
傳值
父組件:
import React from 'react'; import Children from './Children'; class Father extends React.Component { constructor(props) { super(props); this.state = { msg:'父組件的msg' }; } render() { return ( <div> <div>我是父組件</div> <Children msg={this.state.msg}/> </div> ); } } export default Father;
子組件:
import React from 'react'; class Children extends React.Component { constructor(props) { super(props); this.state = { msg:'子組件' }; } render() { return ( <div> <div>子組件</div> <div>{this.props.msg}</div> </div> ); } } export default Children;
效果如下:
傳事件:
父組件:
import React from 'react'; import Children from './Children'; class Father extends React.Component { constructor(props) { super(props); this.state = { msg:'父組件的msg' }; } run=()=>{ alert('給子組件獲取事件') } render() { return ( <div> <div>我是父組件</div> <Children msg={this.run}/> </div> ); } } export default Father;
子組件:
import React from 'react'; class Children extends React.Component { constructor(props) { super(props); this.state = { msg:'子組件' }; } render() { return ( <div> <div>子組件</div> <div>{this.state.msg}</div> <button onClick={this.props.msg}>獲取父組件的事件</button> </div> ); } } export default Children;
效果如下:
獲取父組件的整個實例
父組件:
import React from 'react'; import Children from './Children'; class Father extends React.Component { constructor(props) { super(props); this.state = { msg:'父組件的msg' }; } run=()=>{ alert('給子組件獲取事件') } render() { return ( <div> <div>我是父組件</div> <Children msg={this}/> </div> ); } } export default Father;
子組件:
import React from 'react'; class Children extends React.Component { constructor(props) { super(props); this.state = { msg:'子組件' }; } render() { return ( <div> <div>子組件</div> <div>{this.state.msg}</div> <div>獲取父組件的值{this.props.msg.state.msg}</div> <button onClick={this.props.msg.run}>獲取父組件的事件</button> </div> ); } } export default Children;
效果如下:
2、子組件傳值給父組件,通過ref傳值
父組件:
import React from 'react'; import Children from './Children'; class Father extends React.Component { constructor(props) { super(props); this.state = { msg:'父組件的msg' }; } getData=()=>{ this.setState({ msg:this.refs.children.state.msg }) } render() { return ( <div> <div>我是父組件</div> <div>{this.state.msg}</div> <Children ref='children'/> <button onClick={this.getData}>獲取子組件</button> </div> ); } } export default Father;
子組件:
import React from 'react'; class Children extends React.Component { constructor(props) { super(props); this.state = { msg:'子組件' }; } render() { return ( <div> <div>子組件</div> </div> ); } } export default Children;
效果如下: