【问题标题】:ReactJs TypeError: Cannot assign to read only property 'name' of object '#<Object>'ReactJs TypeError:无法分配给对象'#<Object>'的只读属性'name'
【发布时间】:2018-07-20 10:34:49
【问题描述】:

我正在尝试在组件状态更改时更改输入的名称属性。
简而言之,这就是我想要做的。

 let displayInputElement = (
  <input
    type="text"
    name = {pips}
    placeholder="Type your answer here"
    className=" form-control"
  />
);



 displayInputElement.props.name = "chicken";

但我收到以下错误

TypeError:无法分配给对象“#”的只读属性“名称”

请问我如何在反应中实现以下目标

displayInputElement.props.name = "chicken";
let pips = displayInputElement.props.name;

displayInputElement = (
  <input
    type="text"
    name = "chicken"
    placeholder="Type your answer here"
    className=" form-control"
  />
);

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    我认为你应该将 displayInputElement 作为一个组件,这样你就可以通过 props 参数传递任何你想要的东西

    let DisplayInputElement = (props) =>(
      <input
        type="text"
        name = {props.name}
        placeholder="Type your answer here"
        className=" form-control"
      />
    );
    const state = {
        name:"myrrtle"
    }
    ReactDOM.render(<DisplayInputElement name={state.name} />, mountNode);
    

    你不能通过写 DisplayInputElement.props.name="chicken" 来设置 props,因为 props 是用来读取的。 我刚刚举了一个例子来说明我的意思。希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      道具是只读的。

      您可以创建一个名为 prop 的新变量,然后更改该变量,或者使用回调来更新可以传递给该组件的父组件的属性。

      let newName = displayInputElement.props.name;
      newName = "chicken";
      

      或者是这样的:

      this.state = {
        name: this.props.name;
      }
      
      this.setState({
       name: "chicken";
      }), () => {
        callbackToParent(this.state.name);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-01-08
        • 2019-02-08
        • 2019-11-28
        • 2023-03-13
        • 2021-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多