只能为元素指定className是否很好,这样我就可以通过getElementsByClassName在DOM中找到它吗?
添加类以找到dom元素?当然可以做到这一点,但是 refs 可能是更好的解决方案。
操纵DOM元素?那绝对是不做的。由React管理的DOM的一部分不应操纵我的其他任何反应。
如果您来自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>
}
}
上面的代码未测试,但应该给您一般的想法。
默认情况下,Parent
中的error
状态为false
。在这种状态下,Notification
不会渲染任何内容。如果单击按钮,则error
为true
。在该状态下,Notification
将渲染div
。
尝试声明地思考,而不是毫不局限于思考。
希望会有所帮助。
使用React时,您应该考虑如何使用状态来控制组件的呈现方式。this.setState
执行rerender,这意味着您可以通过更改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>
)
}