我正在尝试将复选框添加到我的 react 组件中,但是当我从 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>
);
如何将函数传递给 child 中的 onChange
最佳答案
您正在使用函数组件
,this
关键字在其中不可用,请直接使用该函数,如下所示:
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
关于javascript - 将函数传递给包含切换的子函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42555274/