【发布时间】:2015-10-30 14:35:16
【问题描述】:
我正在尝试对 React 中的按钮应用简单的状态更改。
'use strict';
class ReactButton extends React.Component {
constructor(props) {
super(props);
this.state = {hovering: false};
}
onClick() {
this.props.handleClick(this.props.text);
}
onHover() {
this.setState({
hovering: !this.state.hovering
});
}
render() {
const color = this.state.hovering ? 'blue' : 'default';
const text = this.state.hovering ? 'Hover Text' : this.props.text;
console.log(color, text);
return (
<button
onClick={this.onClick.bind(this)}
style={{color: color}}
onMouseEnter={this.onHover.bind(this)}
onMouseOut={this.onHover.bind(this)}>
{text}
</button>
);
}
}
ReactDOM.render(
<ReactButton
text={"Original Text"}
handleClick={(e) => console.log('clicked')} />,
document.querySelector('#container')
);
如果您take a look at the demo,您会注意到当按钮悬停时文本颜色变为蓝色,但是当鼠标离开按钮时,文本颜色保持蓝色。该事件被触发,并且状态确实发生了变化,从而触发了重新渲染,正如文本变化所证明的那样。
为什么 react 不更新内联样式?我能做些什么来解决这个问题?
【问题讨论】:
标签: javascript reactjs