我正在 Webpack + ReactJS 项目中创建一个带有 Material UI 的表
我想添加一个带有一个“菜单项”的“图标菜单”,允许用户删除该行和链接的数据。这是(相关的)代码:
export default class GufreFile extends React.Component {
render(){
function alertTest() {
console.log('hello there');
}
return (
<TableRow>
//...
<TableRowColumn>
<IconMenu
iconButtonElement={<IconButton><MoreVertIcon /></IconButton>}
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
>
<MenuItem primaryText="Delete" onTouchTap={ alertTest }/>
</IconMenu>
如果我尝试使用此代码,一切都会完美运行,如果我单击菜单链接,我会收到“你好”。
但是,如果我执行以下操作:
export default class GufreFile extends React.Component {
render(){
function alertTest(data) {
console.log(data);
}
return (
<TableRow>
//...
<TableRowColumn>
<IconMenu
iconButtonElement={<IconButton><MoreVertIcon /></IconButton>}
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
>
<MenuItem primaryText="Delete" onTouchTap={ alertTest( this.props.data.id) }/>
当我重新加载页面时,它会在控制台中显示我的数据 ID。
我不知道这是一个错误,还是我误解了什么。
有人可以帮忙吗?
提前谢谢
最佳答案
您应该在类的构造函数中绑定(bind)处理程序,因为 this
将引用该元素。
另外,您应该将 alertTest
放在 render
函数之外。
export default class GufreFile extends React.Component {
constructor(props){
super(props);
this.alertTest = this.alertTest.bind(this);
}
alertTest = (e) -> {
console.log(e.target); // you can access the element values here
}
// render...
<MenuItem primaryText="Delete" onTouchTap={alertTest}/>
// rest of code
我制作了一个片段作为如何获取 Prop 并通过事件访问元素的示例:
class App extends React.Component {
constructor(props){
super(props);
this.colorMe = this.colorMe.bind(this);
}
colorMe(e){
e.target.style.backgroundColor = '#abcdef';
e.target.innerHTML = this.props.someProp;
}
render() {
return (
<div className="App">
<div id="clickable" onClick={this.colorMe} />
</div>
);
}
}
ReactDOM.render(<App someProp="this is some external prop!"/>, document.getElementById("root"));
#clickable{
width: 150px;
height: 150px;
background-color: #ccc;
text-align: center;
padding: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
关于javascript - ReactJS + Material UI 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43958459/