2017-03-02 82 views
0

我试图复选框添加到我的反应成分,但是当我试图使我从数据拉取从后子它说,功能undifined传递功能,其中包含切换

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

值来自终极版减速

这是我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

您使用的是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