在React中的两个样式对象之间切换



我正试图在单击时更改此组件的样式。我还没有让点击处理程序工作(它实际上是从我在SO上发现的其他代码中提取的,所以如果你对如何实现有建议,我会接受),因为我不确定点击时在这两种风格之间切换的最佳方式是什么。

目前,我尝试在state中使用"class:open",并使用style={this.state.class}来呈现div。这种方法不起作用,因为DOM甚至没有正确加载。这是可能的吗(当然要改变语法),还是另一种方法更好?

请不要建议我使用CSS来做这件事,因为我这样做是为了让自己熟悉React,即使这不是更广泛意义上的"最佳"方法。

class Box extends React.Component {
constructor(...props) {
super(...props)
this.state = {
hover: false,
class: open
}
}
mouseOver = () => this.setState({hover: true});
mouseOut = () => this.setState({hover: false});
handleClick(e){
if (e.target.class === 'open'){
e.target.class = 'closed';
} else{
e.target.class = 'open';
}
}
render(){
const open = {
margin: 5,
width: 30,
height: 30,
backgroundColor: this.state.hover?"#80ffff":"#00e6e6",
display: "inline-block",
textAlign: "center"
};
const closed = {
margin: 5,
width: 30,
height: 30,
backgroundColor: this.state.hover?"#ff4d4d":"#ff0000",
display: "inline-block",
textAlign: "center"
}
return(
<div style={this.state.class} onMouseOver={this.mouseOver} onMouseOut={this.mouseOut} onClick={this.handleClick}></div>
)
}
}

我重构了一些代码,向您展示了一种工作方法(悬停并单击):

在此处创建了一个小提琴:https://jsfiddle.net/mrlew/wt2Ld9rn/

class Box extends React.Component {
constructor(props) {
super(props)
this.state = {
hover: false,
isOpened: false
}
}
mouseOver = () => this.setState({hover: true});
mouseOut = () => this.setState({hover: false});
handleClick(e){
this.setState({isOpened: !this.state.isOpened});
}
render(){
const open = {
margin: 5,
width: 90,
height: 30,
backgroundColor: "#80ffff",
display: "inline-block",
textAlign: "center"
};
const closed = {
margin: 5,
width: 90,
height: 30,
backgroundColor: "#ff0000",
display: "inline-block",
textAlign: "center"
}

return(
<div style={ this.state.isOpened ? open : closed } onMouseOver={this.mouseOver.bind(this)} onMouseOut={this.mouseOut.bind(this)} onClick={this.handleClick.bind(this)}>Hover {this.state.hover ? "!" : "?" }</div>
)
}
}

一些要点:

1) 您必须.bind您的回调函数。来自React文档:

(…)在JavaScript中,类方法默认不绑定。如果你忘了要绑定此.handleClick并将其传递给onClick,将实际调用函数时未定义。

这不是React特有的行为;它是功能的一部分使用JavaScript工作。通常,如果您引用的方法没有()之后,例如onClick={this.handleClick},您应该绑定方法

如果打电话给bind让你很恼火,有两种方法可以解决这如果您使用的是实验属性初始值设定项语法,可以使用属性初始值设定项来正确绑定回调:

2)每次调用.setState时,React都会调度一个新的渲染调用。因此,一般来说,您不必(不应该)自己更改dom(如e.target.class)。

最新更新