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
相关产品推荐
相关产品推荐

