【发布时间】:2017-09-21 22:03:58
【问题描述】:
我是新手,仍在学习 ReactJS 的基础知识。我有一个关于我从书中做的练习的问题。
在本练习中,我需要创建一个事件处理组件,在该组件中我必须使用 state 属性,我的问题是,当我进行上一个练习时,我必须使用 componentDidMount() 方法并在我当前的事件处理上锻炼我不需要。代码示例如下:
var SecondCounter = React.createClass({
//this is our getInitialState method. It initializes the value in our
//component.
getInitialState: function() {
return {
sec: 0
};
},
//this is our timerTick function where we add an increment of one to
// display it as a second everytime setInterval funct gets called.
//this function calls setState to update our component
timerTick: function() {
this.setState({
sec: this.state.sec + 1
});
},
//This function calls our setInterval function after our component
//renders
componentDidMount: function() {
setInterval(this.timerTick, 1000);
},
//this.state displays the value of our state property
render: function() {
var myCompStyle = {
color: "#66FFFF",
fontSize: 50
};
var count = this.state.sec.toLocaleString();
return (
<h1 style={myCompStyle}>{count}</h1>
);
}
/*Our component updates because whenever we call setState and update something
in the state object, our component's render method gets automatically called.*/
});
对于这个练习,它是一个使用 ReactJS 状态方法的基本计数器。在这个项目中,我必须使用所有三个 API。我知道 componentDidMount() 方法在我们的组件被渲染后立即执行。我假设在 setState 更新我们的 sec 属性后,我们的 componentDidMount() 方法会在 UI 中更新它。
以下是我正在做的当前练习:
var CounterParent = React.createClass({
//We know this component is going to change because it has an initial state
//method.
getInitialState: function() {
return {
count: 0
};
},
//This is our event handler function. This is basically what gets
//called everytime our button gets clicked.
increase: function(e) {
this.setState({
count: this.state.count + 1
});
},
render: function() {
//remember a CSS objet property always ends a block of code with a
//semicolon.
var backgroundStyle = {
padding: 50,
backgroundColor: "#FFC53A",
width: 250,
height: 100,
borderRadius: 10,
textAlign: "center"
};
var buttonStyle = {
fontSize: "lem",
width: 30,
height: 30,
fontFamily: "sans-serif",
color: "#333",
fontWeight: "bold",
lineHeight: "3px"
};
return (
//This is where you add the count variable into your Counter2 display property.
//Event Handling: You specify both the event you are listening for and the event
//handler that will get called, all inside your markup.
<div style={backgroundStyle}>
<Counter2 display={this.state.count}/>
<button onClick={this.increase} style={buttonStyle}>+</button>
</div>
);
}
});
注意到没有 componentDidMount() 方法了吗?为什么我不需要在事件处理练习中使用一个?
第一个项目的目的就像一个计时器。它只数秒,永不结束。
第二个项目是点击计数器。因此,每次我单击按钮时,计数属性都会更新。本练习不使用 componentDidMount() 方法。
【问题讨论】:
标签: javascript html css reactjs react-redux