2016-11-16 158 views
2

WeatherForecast組件我需要將函數appColor的返回值傳遞給屬性。然後從WeatherForecast的財產需要被傳遞到app組件的className。新的反應。不知道如何將屬性從子項傳遞給組件。將道具從小孩傳遞給父母React

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

您可以從父傳遞一個函數給孩子,而孩子可以調用與顏色功能(非常像操作的事件處理程序)。當在App中接收到顏色時,使用.setState()將其分配給狀態值,然後在渲染()中將其拾取()

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> 
    ); 
    } 
} 
相關問題