美文网首页
react父子组件通信

react父子组件通信

作者: EWL | 来源:发表于2018-07-15 22:48 被阅读0次

父组件通过props 给子组件传递数据,子组件则是通过调用父组件传给它的函数给父组件传递数据。



class TemperatureShow extends React.Component {
   constructor(props) {
       super(props);
   }
   render() {
       let t = this.props.temperature;
       if(t > 38) {
           return <p>hot</p>;
       }else if(t <= 38 && t >= 20) {
           return <p>cool</p>;
       }else {
           return <p>cold</p>;
       }
   }
}



class TemperatureInput extends React.Component {
   constructor(props) {
       super(props);
       // this.handleTemp=this.handleTemp.bind(this);
   }
   handleTemp(e) {
       this.props.onTemperatureChange(e.target.value);
   }
   render() {
       return (
           <p>
               <label htmlFor="temInput">今天的温度</label>
               <input type="text" name="temInput" value={this.props.temperature} onChange={this.handleTemp.bind(this)}/>
           </p>
       );
   }
}

class TemContainer extends React.Component {
   constructor(props) {
       super(props);
       this.state = {
           temperature: '',
       };
       this.handleTemp = this.handleTemp.bind(this);
   }
   handleTemp(temperature) {
       this.setState({
           temperature: temperature,
       });
   }
   render() {
       let temperature = this.state.temperature;
       return (
           <div>
               <TemperatureInput temperature={temperature} onTemperatureChange={this.handleTemp}></TemperatureInput>
               <TemperatureShow temperature={parseFloat(temperature)}></TemperatureShow>
           </div>
       );
   }
}

ReactDOM.render(
   <TemContainer/>,
   document.getElementById('root'),
);

相关文章

  • React父子组件间通信的实现方式

    React学习笔记之父子组件间通信的实现:今天弄清楚了父子组件间通信是怎么实现的。父组件向子组件通信是通过向子组件...

  • 「React Native」Event Bus,消息总线

    (一)父子间组件通信:   一般使用props,回调函数进行通信。(二)跨组件之间通信:  (1)React Na...

  • react 组件通信

    概述 react中的组件通信问题,根据层级关系总共有四种类型的组件通信:父子组件、爷孙组件、兄弟组件和任意组件。前...

  • React入门基础知识总结

    1.React组件 function组件, class组件,来自ES6的class语法, 2. 父子组件通信 父组...

  • vue中的组件通信

    一、组件通信(组件传值) 1.1父子组件通信 1.2子父组件通信 1.3非父子组件通信(兄弟组件通信)

  • React02-组件通信

    React父子组件之间如何通信父组件传一个函数给子组件,子组件在适当的时候调用这个函数React爷孙组件之间如何通...

  • React 父子组件通信

    通讯是单向的,数据必须是由一方传到另一方。 1.父组件与子组件间的通信。 在 React 中,父组件可以向子组件通...

  • react父子组件通信

    父组件通过props 给子组件传递数据,子组件则是通过调用父组件传给它的函数给父组件传递数据。

  • react父子组件通信

    父组件向子组件通信 回调函数 直接把函数传到组件里面,然后组件里面调用this.props.goDetail函数来...

  • react 父子组件通信

    1. 子组件拿到父组件数据 在父组件中定义一个函数,将其传递到子组件中,子组件调用这个回调函数就可以拿到父组件中的...

网友评论

      本文标题:react父子组件通信

      本文链接:https://www.haomeiwen.com/subject/vrempftx.html