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

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

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')

以下是我的组件

function SectionInput()  {
    const {label} = this.props;
    return (
        <div>
            <form>
                {label && <label>{label}</label>}
                <input type="text" props />
            </form>
        </div>
    );
}

这是我如何使用它

<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')

function SectionInput()  {

    const {label} = this.props;
    return (&lt;div&gt;
        &lt;form&gt;
            {label &amp;&amp; &lt;label&gt;{label}&lt;/label&gt;}
            &lt;input type=&quot;text&quot; props /&gt;
        &lt;/form&gt;
    &lt;/div&gt;
    );
}

the above is my component

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

This is how I'm using it

this is the error

答案1

得分: 0

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

function SectionInput(props) {

    const {label} = props;
    return (<div>
        <form>
            {label && <label>{label}</label>}
            <input type="text" {...props} />
        </form>
    </div>
    );
}

您所做的是:尝试从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.

function SectionInput(props)  {

    const {label} = props;
    return (&lt;div&gt;
        &lt;form&gt;
            {label &amp;&amp; &lt;label&gt;{label}&lt;/label&gt;}
            &lt;input type=&quot;text&quot; props /&gt;
        &lt;/form&gt;
    &lt;/div&gt;
    );
}

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:

确定