在WeatherForecast组件中,我需要将函数的返回值传递appColor给属性。然后从属性WeatherForecast需要被传递到className的app组件。新来的反应。不确定如何将属性从子级传递到组件。
WeatherForecast
appColor
className
app
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()中获取
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> ); } }