Pass prop from child to parent React

后端 未结 1 1980
时光取名叫无心
时光取名叫无心 2020-12-17 06:15

In WeatherForecast component I need to pass the returned value of function appColor into a property. Then the property from WeatherForecast

相关标签:
1条回答
  • 2020-12-17 06:41

    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>
        );
      }
    }
    
    0 讨论(0)
提交回复
热议问题