当从同一组件内注册单击事件时,我试图在 React 组件的一个实例中选择元素(具有特定类的 div)。我不希望从此组件的其他实例中选择具有该类的 div。
我的问题是,在任何给定时间,该组件都可能有任意数量的实例。我是否必须在安装每个组件时为每个组件创建一个唯一的 ID,或者 React 是否可以通过某种方式让我仅引用在组件的特定实例中找到的元素?可以在 React 类中使用回调函数以某种方式完成吗?
例如:
var MyClass = React.createClass({
makeDivsBigger: function() {
...? // How to only select the divs within the current instance?
},
render: function() {
<div className="container">
<div className="dark"></div>
<div className="light"></div>
<div className="bright"></div>
<button onClick={this.makeDivsBigger}></button>
</div>
}
});
最佳答案
有几种方法可以解决这个问题,但您很少想做的一件事是查询 DOM 以查找要处理的元素。这些元素已经在你的 React 宇宙中,所以你不需要找到它们!
更好的方法是让父组件使用内部状态控制元素的大小。
这是一个示例实现:
var MyClass = React.createClass({
getInitialState: function() {
return {
size: ''
};
},
makeDivsBigger: function() {
this.setState({
size: 'bigger'
})
},
render: function() {
<div className="container">
<div className={"dark " + this.state.size}></div>
<div className="light"></div>
<div className="bright"></div>
<button onClick={this.makeDivsBigger}></button>
</div>
}
});
// somewhere in your CSS
.bigger {
height: 500px;
}
关于JavaScript : How to select elements within one instance of a react class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39922301/