2016-11-16 20 views
2

WeatherForecastのコンポーネントで返された関数appColorをプロパティに渡す必要があります。その後、WeatherForecastからの特性はclassNameappのコンポーネントに渡す必要があります。反応するために新しい。子からプロパティへプロパティを渡す方法が不明です。小児から親に小道具を渡す返信

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> 

    ); 
    } 
} 

答えて

6

あなたは親から子への関数を渡すことができ、そして子供が(ほとんどがイベントハンドラのように動作)色でその関数を呼び出すことができます。アプリケーションで色を受け取ったら、.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> 
    ); 
    } 
} 
関連する問題