簡體   English   中英

組件將文本類型的受控輸入更改為不受控制

[英]A component is changing a controlled input of type text to be uncontrolled

這是與此相關的代碼片段:

家長:

class PropertyBar extends Component {
  state = {
    selectedCell: graph.selectedCell,
    cellProperties: []
  }

  updateSelectedCell() {
    if (graph.selectedCell != null) {
      this.setState({
        selectedCell: graph.selectedCell,
        cellProperties: Array.from(graph.selectedCell.value.attributes)
      });
    }
  }

  onChangeHandler = (e) => {
    console.log(e.target.value);
    let cellProperties = [...this.state.cellProperties];
    cellProperties[parseInt(e.target.id)] = e.target.value;
    this.setState({cellProperties});
  }

  renderPropertyList() {
    return this.state.cellProperties.map((key, i) => {
      return <PropertyBarItem name={key.nodeName} value={key.nodeValue} onChange={this.onChangeHandler} key={i} id={i} />
    })
  }

兒童:

class PropertyBarItem extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <ListItem divider={true} className="property-bar-item">
        <TextField
          id={this.props.id.toString()}
          label={this.props.name}
          value={this.props.value}
          margin="dense"
          onChange={(e) => this.props.onChange(e)}
        />
      </ListItem>
    )
  }
}

當我嘗試更改<TextField>value時,它將丟失與之配對的原始label ,並且我認為它與Parent組件狀態之間存在任何關系。

然后我得到這個錯誤:組件正在將文本類型的受控輸入更改為不受控制。 輸入元素不應從受控狀態切換到非受控狀態(反之亦然)。 確定在組件的使用壽命期間使用受控或不受控制的輸入元素。

我知道這可能是由於cellProperties狀態在開始時是一個空數組,但是我的Child組件直到數組中實際有值時才渲染。 我已經對value字段進行了三元操作,例如value={this.props.value ? this.props.value : ""} value={this.props.value ? this.props.value : ""} ,但是當我嘗試鍵入時,它總是返回一個空字符串。

因此,對我的問題的答案是,由於我將NamedNodeMap轉換為Array ,所以我忘記在狀態下添加要在數組中更改的屬性。

因此,而不是cellProperties[parseInt(e.target.id)] = e.target.value; ,我應該分配給的正確值是cellProperties[parseInt(e.target.id)].nodeValue = e.target.value;

現在一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM