小编Wol*_*uff的帖子

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

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

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 函数之后运行渲染函数?

javascript reactjs

5
推荐指数
1
解决办法
3268
查看次数

标签 统计

javascript ×1

reactjs ×1