首页 > 解决方案 > 在按钮单击时按顺序从文本字段中获取值?

问题描述

我的用户界面如下:

![在此处输入图像描述

这些字段来自 API 调用响应。来自 API 响应的字段数量可能会有所不同。我使用 List 实现它,如下所示:

 private _onRenderCell = (field): JSX.Element => {

    return (
        <div>
            <div>
                {field["fieldName"]}
                <br/>                
                {
                    <TextField
                        onChanged={this.onTextChanged}
                    />
                }
                <br/>
            </div>
        </div>
    );
}

public render(): JSX.Element {
    const result: JSX.Element = (
        <FocusZone direction={FocusZoneDirection.vertical}>
            <List
                items={this.props.fields}
                onRenderCell={this._onRenderCell}
            />
        </FocusZone>
    );        

    return (
        <div>              
            {result}
        </div>
    );
}

单击确定按钮时,如何从文本框中获取值,以便 textbox1 值用于名称,textbox2 值用于年龄,textbox3 值用于性别?

标签: reactjsoffice-ui-fabric

解决方案


https://codepen.io/vitalius1/pen/OroprE也许这会有所帮助。考虑到 TextFields 的数量是未知的,我相信这应该会给你一个好的开始。如果这对您有用,请随时关闭该问题。感谢您使用 Fabric,并为这么长时间没有回复表示歉意。

class Content extends React.Component {
  private textFieldRefs: IRefObject<ITextField>[] = [];
  constructor() {
    super(); 

    this.state = {
      inputValues: []
    }
  }

  render() {
    const { inputValues } = this.state;

    return (
      <Fabric className='foo'>
        <List
          items={_items}
          onRenderCell={this._onRenderCell}
        />  
        <DefaultButton
          type="submit"
          onClick={this._onClick}
        >
          Click here
        </DefaultButton>
        {inputValues.map((ref, index) => (
          <div key={index}>{ref}</div>
        ))}
      </Fabric>
   );
 }

  private _onRenderCell = (item) => {
    const ref = React.createRef<ITextField>();
    this.textFieldRefs.push(ref);

    return (
      <div>
        {item.name}
        <br/>                
        <TextField componentRef={ref}/>
        <br/>
      </div>
    );
  }

  private _onClick = () => {
    const {inputValues} = this.state;
    const newValues = [];

    this.textFieldRefs.forEach((ref) => {
      console.log(ref.current.value);
      newValues.push(ref.current.value);
    })

    this.setState({
      inputValues: newValues.concat(inputValues)
    })
  }
}

推荐阅读