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 摘要。