将函数传递给包含切换的子项

时间:2017-03-02 12:15:09

标签: javascript reactjs ecmascript-6 react-redux

我试图在我的反应组件中添加复选框,但是当我从fetch中提取数据后尝试渲染时,它表示该函数是未分解的

TypeError: Cannot read property 'props' of undefined at WeatherInfo

值来自redux reducer

这是我的App.js

toggleCheckboxChange() {
   console.log("a");
}

render() {
  const { cityName, nameOfCity, weatherDescription, windSpeed, temperature, maxTemperature, minTemperature, toogleValue} = this.props;


let weatherInfo;

weatherInfo = <WeatherInfo
      nameOfCity={nameOfCity}
      weatherDescription={weatherDescription}
      windSpeed={windSpeed}
      temperature={temperature}
      maxTemperature={maxTemperature}
      minTemperature={minTemperature}
      toggleValue={toggleValue}
      onChange={() => this.toggleCheckboxChange()}
  />;

WeatherInfo组件

const WeatherInfo = (props) => (
<div>
    <ul>
        <li>{props.nameOfCity}</li>
        <li>{props.weatherDescription}</li>
        <li>{props.windSpeed} m/s </li>
        <li>{props.temperature} °C</li>
        <li>{props.maxTemperature}°C</li>
        <li>{props.minTemperature}°C</li>

        <input
            type="checkbox"
            checked={props.toogleValue}
            onChange={this.props.toggleCheckboxChange}
        />
    </ul>
</div>
);

如何将函数传递给子项中的onChange

1 个答案:

答案 0 :(得分:1)

您使用的是Functional Componentthis关键字不可用,请直接使用此功能,如下所示:

props.function

像这样写:

const WeatherInfo = (props) => (
   <div>
      <ul>
         <li>{props.nameOfCity}</li>
         <li>{props.weatherDescription}</li>
         <li>{props.windSpeed} m/s </li>
         <li>{props.temperature} °C</li>
         <li>{props.maxTemperature}°C</li>
         <li>{props.minTemperature}°C</li>

         <input
            type="checkbox"
            checked={props.myPokemon}
            onChange={(e)=>props.toggleCheckboxChange(e)}
         />
      </ul>
   </div>
);

检查此示例:

class App extends React.Component { 

    change(e){
      console.log(e.target.value);
    }

    render() {
        return (
            <div>
                <Child change={this.change.bind(this)}/>
            </div>
        )
    }
}

let Child = (props)=>{
  return <input onChange={(e)=>props.change(e)}/>
}


ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container'/>

查看此文章:https://www.reactenlightenment.com/react-state/8.4.html