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
277 views
in Technique[技术] by (71.8m points)

reactjs - is there a way to create REFs dynamically then access them

Here is a simple component where I'm adding buttons dynamically:

const MyCompanent = ({ listOfButtons }) => {
    const handleOnKeyUp = (event) => {
        var key = event.keyCode

         // .......
         // access button by REF and do something
    }

    const myButtons = listOfButtons.map((btn) => (
            <button
                key={btn.id}
                onKeyUp={(e) => handleOnKeyUp(e)}
                ref={?????}
            >
                {btn.name}
            </button>
    ))
    
    return (
        <div>
            {myButtons}
        </div>
    )
}

export default MyCompanent

Component gets list of buttons to show as props. I want the button do something specific when I press specific key when button is in focus. So I want to add REFs dynamically for each button to access/manipulate it in handleOnKeyUp function (or anywhere else in this component)

question from:https://stackoverflow.com/questions/65865780/is-there-a-way-to-create-refs-dynamically-then-access-them

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

1 Answer

0 votes
by (71.8m points)
Waitting for answers

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

...