I have a list of components <Task />
each one of them has unique key <Task key={id} />
, The component Task
has an input element inside of it (<div><input type="text" /></div>)
, if i rendered 4 components of Task
how can i get the input element value of them by the key?
this.props.tasks.map((i) => {return (<Task key={i} />);
Task.jsx:
<Form.TextArea id={`newReplyId${this.props.taskId}`} />{' '}
My Question: I want to delete the TextArea id
and get this element by the key of the component?
You could give the Task
an onChange
prop which is a function to call that will give the event and the index of the task in your tasks
array, so you can update the appropriate task in state.
Example
function Task({ task, onChange }) { return ( <div> <input value={task} onChange={onChange} /> </div> ); } class Tasks extends React.Component { state = { tasks: ["", "", "", ""] }; onChange = (event, index) => { const { value } = event.target; this.setState(previousState => { const tasks = [...previousState.tasks]; tasks[index] = value; return { tasks }; }); }; render() { return ( <div> {this.state.tasks.map((task, index) => ( <Task key={index} task={task} onChange={e => this.onChange(e, index)} /> ))} </div> ); } } ReactDOM.render(<Tasks />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>
pass a method to component onchange
this.props.tasks.map((i) => {return (<Task key={i} _onChange={this._onChange}/>);
and handle it in the task component to transfer the key and thevalue changed
_onChange(){
this.props._onChange(data,index);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.