You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js中如何动态获取label值?遇props未定义错误求助

解决React函数组件中Cannot read properties of undefined (reading 'props')错误

你写的是React函数组件,却误用了类组件的this.props写法,这就是报错的核心原因。函数组件的props是通过参数直接传入的,不需要通过this访问。另外你的<input>标签里的props属性是无效冗余代码,需要移除。

修改后的组件代码(两种写法可选)

写法一:先接收props参数再解构

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

写法二:直接在参数中解构props

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

说明

  • 函数组件的props作为第一个参数传入,直接解构就能拿到传入的label属性
  • 移除<input>标签上无效的props属性,避免不必要的语法问题

内容的提问来源于stack exchange,提问作者ishhhhhhhhhhhhh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 11:42:07