Javascript ReactJS+;奇怪的行为
我正在Webpack+ReactJS项目中创建一个带有材质UI的表 我想添加一个带有一个“菜单项”的“图标菜单”,允许用户删除行和链接数据。以下是(相关)代码:Javascript ReactJS+;奇怪的行为,javascript,reactjs,material-ui,Javascript,Reactjs,Material Ui,我正在Webpack+ReactJS项目中创建一个带有材质UI的表 我想添加一个带有一个“菜单项”的“图标菜单”,允许用户删除行和链接数据。以下是(相关)代码: 导出默认类GufreFile扩展React.Component{ render(){ 函数alertTest(){ log('hello here'); } 返回( //... 如果我尝试使用这段代码,一切都会很完美,如果我点击我的菜单链接,我会得到“你好” 但是,如果我执行以下操作: export default class Guf
导出默认类GufreFile扩展React.Component{
render(){
函数alertTest(){
log('hello here');
}
返回(
//...
如果我尝试使用这段代码,一切都会很完美,如果我点击我的菜单链接,我会得到“你好”
但是,如果我执行以下操作:
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) }/>
导出默认类GufreFile扩展React.Component{
render(){
功能警报测试(数据){
控制台日志(数据);
}
返回(
//...
当我重新加载页面时,它将使我的数据id显示在控制台中
我不知道这是不是一个错误,或者我是否误解了什么
有人能帮忙吗
提前感谢您应该在类的构造函数中绑定处理程序,因为
此
将引用元素。您还应该将
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
非常感谢,我现在知道为什么我之前会遇到这些问题了!但是,我的主要问题还没有解决:如果我使用下面的`alertTest=(data)->{console.log(data);//您可以使用onTouchTap={this.alertTest(this.props.data.id)
在这里访问元素值}`(我使用onTouchTap和onClick进行了测试)您不应该在渲染中调用该方法,只应将其作为refonTouchTap={alertTest}传递
我想这样更安全,但话说回来,有没有办法做到这一点?这不是安全问题,而是性能问题。当你创建这样一个函数时,你不会向函数传递引用,而是创建一个函数实例,这会在每次渲染时创建它。这对性能非常有害。当你在构造函数中绑定它时r您只实例化了一次函数。为什么还要向该函数传递一个参数?很抱歉没有提前回答,再次感谢您的回答!正如您在我的原始问题中看到的,我正在创建一个表。但是,我需要能够删除一行,我知道的唯一方法是通过Aja将id传递给控制器x请求。所以我真的不知道有什么其他方法可以这样做
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