在很多例子中,我看到要管理react组件内的状态,你必须使用getInitialState,例如在这个例子中。
var LikeButton = React.createClass({
getInitialState: function() {
return {liked: false};
},
handleClick: function(event) {
this.setState({liked: !this.state.liked});
},
render: function() {
var text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<p onClick={this.handleClick}>
You {text} this. Click to toggle.
</p>
);
}
});
但是在ES6语法中使用getInitalState()将不再起作用。那么如何使用ES6语法管理react组件中的状态呢?
一个例子是
// Future Version
export class Counter extends React.Component {
static propTypes = { initialCount: React.PropTypes.number };
static defaultProps = { initialCount: 0 };
state = { count: this.props.initialCount };
tick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div onClick={this.tick.bind(this)}>
Clicks: {this.state.count}
</div>
);
}
}
由于
答案 0 :(得分:8)
RealDate: CDate(NumericDate)
42408 -> 2016-02-08
实例变量来重构getInitialState
方法。
this.state
注意:您必须将方法绑定到组件实例
在ES6 +中,您可以使用Property initializers功能
import React, { Component } from 'react';
class LikeButton extends Component {
constructor() {
super();
this.state = { liked : false };
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({
liked : !this.state.liked
});
}
render() {
const text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<p onClick={this.handleClick}>{`You ${text} this. Click to toggle.`}</p>
);
}
}
注意:这是Stage 0提案。
注意:我将import React, { Component } from 'react';
class LikeButton extends Component {
state = {
liked : false
}
render() {
const text = this.state.liked ? 'like' : 'haven\'t liked';
const handleClick = ()=>{
this.setState({
liked : !this.state.liked
});
}
return (
<p onClick={this.handleClick}>{`You ${text} this. Click to toggle.`}</p>
);
}
}
如此定义的constructor
作为嵌套函数放在handleClick
参考: React official docs / Article
答案 1 :(得分:1)
在ES6中,您在构造函数中初始化状态。即:
constructor(props) {
super(props)
this.state = {} //or whatever
}
您可以在official docs
中阅读更多内容答案 2 :(得分:-1)
我认为问题可能与<p>
标记内的文字有关。试试这个代码的大小:
const LikeButton = React.createClass({
getInitialState() {
return {
liked : false
};
},
handleClick() {
this.setState({
liked : !this.state.liked
});
},
render() {
const text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<p onClick={this.handleClick}>{`You ${text} this. Click to toggle.`}</p>
);
}
});