我刚接触使用react并遇到了问题:
未捕获的TypeError:无法读取null的属性"setState".
基本上我要做的是,用户可以点击三个不同的标题,点击后,它将呈现特定于该标题的特定模板.这是我正在使用的代码,它给了我这个错误:
class Selection extends React.Component {
constructor(props) {
super(props);
this.state = {selections: [], donateActive: true, fundraiseActive: false, speakActive: false };
}
componentDidMount() {
this.setState({
selections: selectionData.selections
})
}
componentWillUnMount(){
console.log("unmounted!");
}
donateOnClick() {
this.setState({ donateActive: true, fundraiseActive: false, speakActive: false});
}
fundraiseOnClick() {
this.setState({ fundraiseActive: true, donateActive: false, speakActive: false});
}
speakOnClick() {
this.setState({ speakActive: true, fundraiseActive: false, donateActive: false});
}
donateTemplate() {
return (
<div>
<h1>donate template</h1>
</div>
)
}
fundraiseTemplate() {
return (
<div>
<h1>fundraise template</h1>
</div>
)
}
speakTemplate() {
return (
<div>
<h1>speak template</h1>
</div>
)
}
render() {
return(
<div>
<div className="col-sm-6 col-sm-push-6 right">
<div className="right-content-container">
<div className="selections">
<h3>You can</h3>
<h1 onClick={this.donateOnClick} className="selection active" id="selection-donate">donate</h1>
<h1 onClick={this.fundraiseOnClick} className="selection" id="selection-fundraise">fundraise</h1>
<h1 onClick={this.speakOnClick} className="selection" id="selection-speak">speak up</h1>
<hr></hr>
</div>
<div>
{
if (this.state.donateActive) {
this.donateTemplate()
}
if (this.state.fundraiseActive) {
this.fundraiseTemplate()
}
if (this.state.speakActive) {
this.speakTemplate()
}
}
</div>
</div>
</div>
<div className="col-sm-6 col-sm-pull-6 left">
<div className="left-content-container">
<img className="img-responsive hidden-xs" src="./images/selections/.jpg" alt=""/>
<img className="img-responsive hidden-sm hidden-md hidden-lg" src="./images/selections/.jpg" alt=""/>
</div>
</div>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
另外,我不确定我是否能够在方法IF内部使用语句,有没有更好的方法呢?return()render()
任何帮助将不胜感激.
你的问题与this绑定有关.this除构造函数和生命周期方法外,React不会自动将React组件绑定到值.为了解决这个问题,在你的构造,每个功能要绑定添加此this为
constructor(props) {
super(props);
this.donateOnClick = this.donateOnClick.bind(this);
// other function bindings
}
Run Code Online (Sandbox Code Playgroud)
至于你的if陈述问题,只要if语句被包含在内{},你就可以使用它们.花括号向JSX解析器指示它们内部的任何内容都应该被评估为javascript,因此任何有效的javascript都可以放在它们内部.
更新:不确定为什么这些if语句抛出了意外的令牌错误,但试试这个:
<div>
{ this.state.donateActive ? this.donateTemplate() : null }
{ this.state.fundraiseActive ? this.fundraiserTemplate() : null }
{ this.state.speakactive ? this.speakTemplate() : null }
</div>
Run Code Online (Sandbox Code Playgroud)
那是使用三元if语句.如果您不熟悉语法:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
如果这不起作用,请使用更详细的错误消息更新您的问题.特别是,我很想知道它说的是什么标记是出乎意料的
| 归档时间: |
|
| 查看次数: |
4924 次 |
| 最近记录: |