繁体   English   中英

获取动态填充的输入值React.js

[英]Getting a value of inputs populated Dynamically React.js

我对React很陌生,我之前从事过本机React工作,所以我对框架非常熟悉。 基本上我有一个对象数组,可以说包含5个项目。 我根据对象的数量填充视图,因此,如果有5个对象,则我的map函数将同时填充5个输入和5个输入。 我的问题是如何获取每个输入的值? 这是我的代码:

array.map(map((item, index) => (
    <h1> item.title </h1>
    <input value={input from user} />
)

您必须使用状态并使用onChange手动更新值

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    value: ''
    }
  }
  handleInputChange(e) {
    this.setState({
        [e.target.name]: e.target.value
    });
  }
  render () {
    return (
      <div>
        <input value={this.state.value} onChange={(e) => {this.handleInputChange(e)}} />

      </div>
    )
  }
}

ReactDOM.render(<App />,  document.getElementById('app'))

一种快速的解决方案是对所有输入值使用数组。

const Inputs = ({array}) => {
    const [inputs, setInputs] = useState([]);

    const setInputAtIndex = (value, index) => {
        const nextInputs = [...inputs]; // this can be expensive

        nextInputs.splice(index, 1, value);

        setInputs(nextInputs);
    }

    return (
        ...
        array.map((item, index) => (
            <div key={index}>
                <h1>{item.title}</h1>
                <input
                    value={inputs[index]}
                    onChange={({target: {value}) => setInputAtIndex(value, index)}
                />
            </div>
        )
        ...
    );
}

请记住,在这种情况下,每次更改inputs都会使用[...inputs]复制inputs状态数组。 如果您的阵列包含很多项目,这是一个性能问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM