将支持从孩子传给父母React [英] Pass prop from child to parent React

查看:108
本文介绍了将支持从孩子传给父母React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WeatherForecast 组件中,我需要将函数 appColor 的返回值传递给属性。然后需要将 WeatherForecast 中的属性传递到 app app c>组件。新的反应。不知道如何将属性从子节点传递给组件。

In WeatherForecast component I need to pass the returned value of function appColor into a property. Then the property from WeatherForecast needs to be passed into className of app component. New to react. Not sure how to pass property from child to component.

class WeatherForecast extends Component {

  appColor(weatherData) {
    //Check for condition and return value
    return "example-color1"
  }

  render() {
    /************************************
    // Need to Pass returned value of Function into propery or variable?
    /************************************/ 
    let bgColor = appColor(weatherData);

    return (
      <div className="text-center col-xs-12">

         <h1 id="temp">{this.displayTemp(this.props.weather)}</h1>
         <h1>{this.displayCity(this.props.weather)}</h1> 

      </div>
    );
  }
}



export default class App extends Component {

  render() {
    return (
      <div className={"app-container" + this.AppColorPropertyClass}>

        <div className="main-wrapper">

            <WeatherForecast bgColorPropertyClass={this.AppColorPropertyClass} />

        </div> 

      </div>  

    );
  }
}


推荐答案

你可以将函数从父级传递给子级,子级可以使用颜色调用该函数(几乎像事件处理程序一样运行)。当在App中收到颜色时,使用.setState()将其指定为状态值,然后在render()中拾取它。$ / b>

You can pass a function from the parent to the child, and the child can call that function with the color (pretty much operates like an event handler). When the color is received back in App, assign it to a state value using .setState() which will then get picked up in render()

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = { appColorClass: 'some-default-color' };
  }

  setAppColor(colorClass) {
    this.setState({ appColorClass: colorClass });
  }

  render() {
    return (
      <div className={"app-container" + this.state.appColorClass}>

        <div className="main-wrapper">

          <WeatherForecast getBgColorPropertyClass={ color => this.setAppColor(color) } />

        </div>

      </div>

    );
  }
}


class WeatherForecast extends Component {
  componentWillMount() {
    if (this.props.getBgColorPropertyClass) {
      // TODO: Get "weatherData" from somewhere (maybe from this.props.weather ??)
      this.props.getBgColorPropertyClass(this.appColor(weatherData));
    }
  }

  appColor(weatherData) {
    //Check for condition and return value
    return "example-color1"
  }

  render() {
    return (
      <div className="text-center col-xs-12">

         <h1 id="temp">{this.displayTemp(this.props.weather)}</h1>
         <h1>{this.displayCity(this.props.weather)}</h1> 

      </div>
    );
  }
}

这篇关于将支持从孩子传给父母React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆