所以我有以下代码,它利用了 Bootstrap 的按钮样式和功能:
import React from 'react';
import DashboardActions from '../../action/dashboard.js';
export class StatFilter extends React.Component
{
constructor(props) {
super(props);
this.state = {
selection: this.props.initialSelection
};
}
render() {
return (
<div className="btn-group">
<button ref="viewButton" type="button" className="btn btn-danger dropdown-toggle" data-toggle="dropdown"
onChange={DashboardActions.seeValue.bind(null, React.findDOMNode(this.refs.viewButton).value)}>
<span>{this.props.initialSelection}</span>
<span className="caret"></span>
<span className="sr-only">Toggle Dropdown</span>
</button>
<ul className="dropdown-menu">
<li><a>Revenue</a></li>
<li><a>Trends</a></li>
<li><a>Statistics</a></li>
</ul>
</div>
);
}
}
在 render
函数中,我的 StatFilter
将一个 Action 附加到一个事件。我希望通过该绑定(bind)发生的是将 viewButton
按钮的值传递给操作。换句话说,当按钮的值发生变化时,StatFilter
将发送一个操作,让我的应用知道它的值已发生变化。
我尝试这样做的方法是使用 bind()
将 viewButton
的值传递给操作。然而,这给了我警告:
t is accessing getDOMNode or findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.
错误:
Uncaught TypeError: Cannot read property 'value' of null
虽然我确定我做错了,但警告是否也告诉我一些事情?我应该在渲染函数中处理所有这些逻辑吗?如果没有,那么我应该把它放在哪里?另外,为什么上面的代码不起作用?
最佳答案
在渲染方法返回中调用 findDOMNode
是问题所在。您不能直接在事件处理程序中调用函数,而是必须向事件处理程序传递一个回调。这不会在组件呈现时调用函数调用,而是在事件发生时调用。
export class StatFilter extends React.Component
{
constructor(props) {
super(props);
this.state = {
selection: this.props.initialSelection
};
}
handleChange(){
DashboardActions.seeValue(React.findDOMNode(this.refs.viewButton).value);
}
render() {
return (
<div className="btn-group">
<button ref="viewButton" type="button" className="btn btn-danger dropdown-toggle" data-toggle="dropdown"
onChange={this.handleChange}>
<span>{this.props.initialSelection}</span>
<span className="caret"></span>
<span className="sr-only">Toggle Dropdown</span>
</button>
<ul className="dropdown-menu">
<li><a>Revenue</a></li>
<li><a>Trends</a></li>
<li><a>Statistics</a></li>
</ul>
</div>
);
}
}
关于javascript - 如何将数据从元素传递到 ReactJS 中的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31364139/