如何在 "Father" 组件中获取 `textField` 的值

How to get the values of `textField` in the "Father" component

我在我的用户自定义 component 中设置了一个 material-ui/TextField。用户定义的 component 被命名为 LabelTextField。我在名为 TextList 的用户定义 component 中渲染了几个 LabelTextField。我的问题是如何在 TextList 组件中获取 textField 的值。

视图组件中的 TextList 组件旁边有一个按钮。当有人点击按钮时,我将保存所有 TextField 值。 我会在 TextList 组件中 post 一个网络请求,将值保存到后端。

我正在使用 Redux。每个 material-ui/TextField 都应该在 onChange 回调函数中调度 value 吗?

onChange在本站底部:

http://www.material-ui.com/#/components/text-field

我的中心代码:

LabelTextField:

  textChangeFun = (value) => {
    
  }


  render() {
    return (
        <div>
          <div style={{fontSize:0}}>
            <div style={inlineStyle}>
              <FlatButton  disableTouchRipple={true}  disabled={true} label={this.props.labelValue} />
            </div>
            <div  style={inlineStyle}>
              <TextField
                  hintText={this.props.textValue}
              />
            </div>
          </div>
        </div>
    );
  }

TextList:

render(){
     return (
         <div>
           {demoData.map((item,id) =>
           <LabelTextField key={id} labelValue={item.label} textValue={item.text} ></LabelTextField>
             )}
         </div>
     )
   }

您需要为 LabelTextField 提供更改事件的处理程序。

class LabelTextField extends React.Component {

  onChange(e) {
    this.props.onChange({ id: this.props.id, value: e.currentTarget.value })
  }

  render() {
    return (
        <div>
          <div style={{fontSize:0}}>
            <div style={inlineStyle}>
              <FlatButton  disableTouchRipple={true}  disabled={true} label={this.props.labelValue} />
            </div>
            <div  style={inlineStyle}>
              <TextField
                  hintText={this.props.textValue}
                  onChange={this.onChange.bind(this)}
              />
            </div>
          </div>
        </div>
    );
  }
}

class TextList extends React.Component {
  constructor() {
    super();
    this.state.textFields = {}; // TODO: get initial state from demoData
    this.onTextFieldChange = this.onTextFieldChange.bind(this);
  }

  onTextFieldChange = ({ id, value }) {
    const { textFields } = this.state;
    textFields[id] = value;
    this.setState({ textFields }); 
  } 

  render(){
     return (
         <div>
           {demoData.map((item,id) =>
           <LabelTextField key={id} labelValue={item.label} textValue={item.text} onChange={this.onTextFieldChange} ></LabelTextField>
             )}
         </div>
     )
   }
}

这样,只要文本字段发生变化,就会调用 onTextFieldChange 处理程序并更新 TextList 的状态。

如果你的情况比较复杂,可以考虑使用redux甚至http://redux-form.com/6.5.0/