【问题标题】:ReactJS _ name custom attribute - The custom attribute of my React component returns "undefined"ReactJS _ 名称自定义属性 - 我的 React 组件的自定义属性返回“未定义”
【发布时间】:2019-01-24 19:01:13
【问题描述】:

我正在使用 ReactJS。

我正在尝试获取我的 ReactJS 组件的自定义属性 -name-。 e.target.name 在我的控制台上返回“未定义”。

我不知道为什么。

这是我的 sn-p-you can test it on CodeSandbox更新:sn-p 已更新为有效的解决方案。在编写这些行时,我使用 React 16.4.2 + NextJS 6.1.1。

export default class view_recipes extends Component {
  
  state={ 
    displayCategoryMenu:true,
    displayBox1: false, 
    displayBox2: false,
    displayBox3: false,
    displayBox4: false,
    displayBox5: false,
    displayBox6: false,
  };

  handleDisplaying = (e) => { 
    e.preventDefault();
    console.log("EVENT: ",  e.currentTarget.attributes.reactname.value )
    let display = { 
      displayCategoryMenu:false,
      displayBox1: false, 
      displayBox2: false,
      displayBox3: false,
      displayBox4: false,
      displayBox5: false,
      displayBox6: false,
    };

    console.log("display: ", display)
    
  }

  render() {
    return (
    <Layout>
      <div className={style.page}>
        <div 
        style={this.state.displayCategoryMenu? {} : { display: 'none' }}
        className={style.category_grid} > 

            <div reactname="displayBox1" onClick={(e) => this.handleDisplaying(e)} > 
              <Populater_s_ComponentHere />
            </div>
        </div>
           // The functionalities above determine if I display this component
           <div
           style={this.state.displayBox1 ? {} : { display: 'none' }}
           > 
              <SomeComponentHere />   
           </div> 
      </div>
    </Layout>
    )
  }
}

Devin Fields 和 Hemari Davari 的解决方案在上述 sn-p 上效果很好。可悲的是,我的代码块似乎带有这些伟大的解决方案。因此,我重构了我的沙箱,使其更接近我的代码的实际情况。您将看到属性返回未定义。

这里是重构的代码片段:https://codesandbox.io/s/l5k5ynv9vq

谢谢

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    它应该在 e.target.attributes 下。我刚刚检查了自己,它就在那里。具体来说,e.target.attributes.name.value。

    Here the functional snippet.

    另请参阅这些答案,它们构成了将属性传递给 onClick 方法的不同方法:div's id attribute is undefined/not getting captured onClick in a react app

    您正在使用“this.handleDisplaying”,但问题是调用该方法时上下文正在更改,并且该上下文不包含任何 handleDisplaying 方法。如果您删除“this”并简单地调用 handleDisplaying 方法,它会按预期工作。这对您的情况应该没问题,因为您没有将方法传递给孩子并且要求上下文保持不变。

    此 sn-p 显示了删除“this”的替代方法,即将组件转换为类:https://codesandbox.io/s/m7qr67o23x

    【讨论】:

    • 谢谢,但是,arf!我已经看到我的代码不适用于此解决方案。我重构了我的 sn-pot 使其更接近我的代码的实际情况。如果你想引起注意,这里是新的沙箱 sn-p:codesandbox.io/s/l5k5ynv9vq
    • @Webman 是因为你在找'name',但是属性属性是'reactname'。抱歉,我的答案中的 sn-p 已更改。您可以将它们都改回“名称”。
    • 是的,我的错,它仍然无法在我自己的代码上运行 - 显示未定义 - 但我会花一些时间来监控原因,谢谢
    • 你能发布你的实际组件吗?如果我看到您的实际代码,我可以发现问题。
    • 好的,我已经用更完整的 sn-p 更新了我的帖子
    【解决方案2】:

    你可以得到

    e.target.attributes["name"] or e.target.attributes[0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多