英文:
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 (<div>
<form>
{label && <label>{label}</label>}
<input type="text" props />
</form>
</div>
);
}
the above is my component
<SectionInput label="Title"/>
This is how I'm using it
答案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 (<div>
<form>
{label && <label>{label}</label>}
<input type="text" props />
</form>
</div>
);
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论