【发布时间】:2018-03-11 20:04:09
【问题描述】:
只为元素指定 className 这样我以后可以通过 getElementsByClassName 在 DOM 中找到它进行操作是否很好?
【问题讨论】:
只为元素指定 className 这样我以后可以通过 getElementsByClassName 在 DOM 中找到它进行操作是否很好?
【问题讨论】:
添加一个类来查找 DOM 元素?当然可以,但refs 可能是更好的解决方案。
操作 DOM 元素?那是绝对不行的。由 React 管理的 DOM 部分除了 React 本身之外,不应该被其他任何东西操作。
【讨论】:
如果你有 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 执行重新渲染,这意味着您可以通过更改 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>
)
}
【讨论】:
{this.state.show ? <Component/> : null }。 <Component/> 不会被挂载,直到 this.state.show 更改为 true,就像我的不透明度示例一样。