reactjs / reactjs/react.dev

Improve uncontrolled form components documentation

未关闭
#1,126 0 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
JavaScript
星标
11.8k
派生
7.9k
平均合并
1 天 11 小时
30 天内合并 PR
11

描述

Referring to Uncontrolled Components I think there are some pitfalls to be documented when using them.


Rendering uncontrolled components correctly

In contrast to controlled components, uncontrolled components using defaultValue, defaultChecked should not be rendered until the default is present, respectively <select> should not be rendered until the default and the <option> children are present, because the functionality of the defaultValue or defaultChecked is only given after mounting, not on updating.

Not being rendered can be achieved in two different ways:

  1. simply don't render it e.g. return null
  2. force rerender with changing key on it

If you strictly don't want partial results in your form use "B", else "C" would work.

// A)
// bad
class UncontrolledMotd extends React.Component {

  state = {
    text: null
  };

  async componentDidMount() {
    const res = await fetch('/motd');
    const text = await res.text();
    this.setState({text});
  }

  render() {
    // bad default
    return (
      <input type="text" defaultValue={this.state.text} />
    );
  }
}
// B)
// better: no render, no placeholder
class UncontrolledMotd extends React.Component {

  state = {
    loaded: false,
    text: null
  };

  async componentDidMount() {
    const res = await fetch('/motd');
    const text = await res.text();
    this.setState({loaded: true, text});
  }

  render() {
    if (!this.state.loaded) {
      return null;
    }

    return (
      <input type="text" defaultValue={this.state.text} />
    );
  }
}
// C)
// better: placeholder, using key
class UncontrolledMotd extends React.Component {

  state = {
    loaded: false,
    text: null
  };

  async componentDidMount() {
    const res = await fetch('/motd');
    const text = await res.text();
    this.setState({loaded: true, text});
  }

  render() {
    return (
      <input key={!this.state.loaded ? 'preview' : 'final'} type="text" defaultValue={this.state.text} />
    );
  }
}

Did not test code above, but the idea in my current project and it works.
What do you think?

Regards Philipp

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先查看链接的 Uncontrolled Components 文档以及此 issue 中提出的示例。验证非受控组件的行为,并确定应如何将其中的陷阱纳入文档;当相关指导和经过测试的示例都已清晰地整合进去时,即视为完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, react
领域
documentation
Issue 类型
文档
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。