Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
77 views
in Technique[技术] by (71.8m points)

javascript - ReactJS - update component (generated from a list) in the same div

It's a basic question but I searched for a guide without success...

I want to have a list of dropdowns and inputs and each dropdown will change the input next to it.

var list = [{ name: "foo1"}, {name: "foo2"}];


return (
    {list.map( (name) => {
        return (<div>
                    <dropdown data={someData} 
                        onChange={(ev) => {
                                       if(ev.value == 'clearIt') 
                                            <CHANGE THE NEAR INPUT VALUE>
                                     }
                             }/>
                     <input value={name.name} />
                </div>)
     })});

I don't want to use DOM nor ref cause I understood that it's better to avoid it.

Any suggestions? Or maybe the ref is the only option?

Thanks

question from:https://stackoverflow.com/questions/65882608/reactjs-update-component-generated-from-a-list-in-the-same-div

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So you can achieve this by doing the following steps:

  • Create a new component and move the dropdown and input to this new component.
  • Add state to your component by following this example: https://reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class
  • Add an event listener onChange to the dropdown with an event handler which can update the state you created in the first step. (Remember to bind the handler in the constructor.
  • Add the new component within the div element of this example you gave and pass the relevant data you need to the new component you created.

This should allow you to update only the input next to the dropdown. Also it allows you to have different data for each dropdown you created.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...