如何在React.js中动态获取标签值?

huangapple go评论76阅读模式
英文:

How to take label values dynamically in React js?

问题

I am trying to get an attribute input for the label tag while rendering the component. Using props to do this but it's giving the following error-

无法读取未定义的属性(读取 'props')
类型错误:无法读取未定义的属性(读取 'props')

以下是我的组件

  1. function SectionInput() {
  2. const {label} = this.props;
  3. return (
  4. <div>
  5. <form>
  6. {label && <label>{label}</label>}
  7. <input type="text" props />
  8. </form>
  9. </div>
  10. );
  11. }

这是我如何使用它

  1. <SectionInput label="Title"/>

这是错误的截图:错误截图

英文:

I am trying to get a attribute input for the label tag while rendering the component. Using props to do this but its giving the following error-

Cannot read properties of undefined (reading 'props')
TypeError: Cannot read properties of undefined (reading 'props')

  1. function SectionInput() {
  2. const {label} = this.props;
  3. return (&lt;div&gt;
  4. &lt;form&gt;
  5. {label &amp;&amp; &lt;label&gt;{label}&lt;/label&gt;}
  6. &lt;input type=&quot;text&quot; props /&gt;
  7. &lt;/form&gt;
  8. &lt;/div&gt;
  9. );
  10. }

the above is my component

  1. &lt;SectionInput label=&quot;Title&quot;/&gt;

This is how I'm using it

this is the error

答案1

得分: 0

由于您正在使用函数组件,可以通过函数的参数访问它的props。

  1. function SectionInput(props) {
  2. const {label} = props;
  3. return (<div>
  4. <form>
  5. {label && <label>{label}</label>}
  6. <input type="text" {...props} />
  7. </form>
  8. </div>
  9. );
  10. }

您所做的是:尝试从this中访问props,但函数组件中不会有this。在类组件中可以使用this.props来访问它。

英文:

Since you are using a functional component, accessing props from it is done by using the parameter of the function.

  1. function SectionInput(props) {
  2. const {label} = props;
  3. return (&lt;div&gt;
  4. &lt;form&gt;
  5. {label &amp;&amp; &lt;label&gt;{label}&lt;/label&gt;}
  6. &lt;input type=&quot;text&quot; props /&gt;
  7. &lt;/form&gt;
  8. &lt;/div&gt;
  9. );
  10. }

What you are doing is: Accessing the props from this that does not have it. Accessing it with this.props can be done with class components.

huangapple
  • 本文由 发表于 2023年5月29日 22:42:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76358258.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定