【问题标题】:Pass prop from child to parent React将 prop 从子级传递给父级 React
【发布时间】:2016-11-16 23:19:09
【问题描述】:

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

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>  

    );
  }
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您可以将一个函数从父级传递给子级,子级可以使用颜色调用该函数(几乎像事件处理程序一样操作)。当在 App 中接收回颜色时,使用 .setState() 将其分配给状态值,然后在 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>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-09
      • 2020-12-31
      • 2018-03-09
      • 1970-01-01
      • 2023-01-30
      • 2016-09-26
      • 1970-01-01
      相关资源
      最近更新 更多