为元素指定className是否合适,以便稍后可以通过getElementsByClassName在DOM中找到它进行操作?
答案 0 :(得分:2)
添加一个类来查找DOM元素?当然你可以做到这一点,但refs可能是更好的解决方案。
操纵DOM元素?这绝对不行。除了React本身之外,由React管理的DOM部分不应该被操纵。
答案 1 :(得分:1)
如果你来自jQuery背景或类似的东西,你将倾向于直接操纵元素:
<div class="notification">You have an error</div>
.notification {
display: none;
color: red;
}
.show {
display: block;
}
handleButtonClick(e) {
$('.notification').addClass('show');
}
在React中,您可以通过声明您的元素(组件)在应用程序的不同状态下应该执行的操作来实现此目的。
const Notification = ({ error }) => {
return error
? <div className="notification">You have an error</div>
: null;
}
class Parent extends React.Component {
state = { error: false };
render() {
return (
<div>
<Notification error={this.state.error} />
<button onClick={() => this.setState({ error: true })}>
Click Me
</button>
}
}
上面的代码没有经过测试,但应该给你一般的想法。
默认情况下,error
中的Parent
状态为false
。在该状态下,Notification
将不会呈现任何内容。如果点击该按钮,error
将为true
。在该州,Notification
将呈现div
。
尝试以声明的方式而不是强制性地思考。
希望有所帮助。
答案 2 :(得分:0)
使用React时,您应该考虑如何使用state来控制组件的呈现方式。 this.setState
执行重新渲染,这意味着您可以通过更改this.state
来控制元素的呈现方式。这是一个小例子。我使用this.state.show
作为布尔值来更改HTML元素的不透明度。
constructor(props) {
super(props)
this.state = {
show: true
}
}
handleClick() {
this.setState({show: false})
}
render() {
const visibility = this.state.show ? 1 : 0
return (
<button style={{opacity: visibility} onClick={() => this.handleClick()}>
Click to make this button invisible
</button>
)
}