react props 在构造函数中未定义并存在于渲染中

Wol*_*uff 5 javascript reactjs

我正在尝试创建一个受控文本区域。

class TextArea extends React.Component {
  constructor(props) {
    super(props);
    this.state= {
        text: this.props.initial
    };
    this.handleChange = this.handleChange.bind(this);
  }

handleChange(event) {
    //some handle
}

render() {
    return (
        <textarea
          value={this.state.text}
          placeholder={this.props.initial}
          onChange={this.handleChange}
        />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,如果我this.props.initial在构造函数中console.log ,我会得到一个未定义的。

但占位符有效。

我想要做的是抛弃占位符并设置一个初始值,用户可以编辑和复制并与之交互。(基本上是普通文本而不是占位符,但我不能这样做,因为它不起作用)

我究竟做错了什么?

编辑:我传递props.initial给 textarea 的方式:

<TextArea
  initial={this.state.json.initial}
  text={this.state.json.text}
  changeHandler={this.handleChange}
/>
Run Code Online (Sandbox Code Playgroud)

我从 $.getJSON 调用中获取 json 并且我认为 textarea 在 json 调用完成之前被呈现。有没有什么办法可以只在 componentWillMount 函数之后运行渲染函数?

Mar*_*aru 0

要理解的重要部分是构造函数已经将 props 作为参数,因此您可以直接在构造函数中访问 props 作为propsthis.props只要您在构造函数内,就不需要通过访问它

constructor(props) {
  super(props);
  this.state= {
    text: props.initial
  }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码应该可以工作


然而,这是构建组件的更好方法,它还应该解决运行时没有值的TextArea问题props.initial

首先需要handleChange在父组件中准备好方法

class ParentComponent extends Component {
  constructor(props) {
    super(props)
    this.state = {
      myTextArea: ''
    }

    this.handleChange = this.handleChange.bind(this)
  }

  handleChange (e) {
    this.setState({myTextArea: e.target.value})
  }

  render () {
    return (
      <TextArea
        value={myTextArea}
        onChange={this.handleChange}
      />
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

在文本区域组件上,您在定义文本区域的 onchange 方法时引用通过 props 传递的 onchange 方法。

<textarea
  value={this.props.value}
  placeholder="Something"
  onChange={this.props.handleChange}
/>
Run Code Online (Sandbox Code Playgroud)

这种方法的好处是,第一,调用 textarea 的元素将始终具有更新的值,第二,该子元素不需要具有状态。它使管理大型 React 应用程序变得更容易,并且一旦您开始尝试实现 Redux 或类似框架来为您处理状态,它就是正确的心态