简体   繁体   English

将单选按钮设置为默认选中,仅当在 React 中传递道具时

[英]Setting a radio button to be checked as default, only when passing in a prop in React

Suppose I have a function like this in React假设我在 React 中有这样一个 function

function Stars({handleStarClick, starClicked}) {

    if (starClicked === 3) {
      document.getElementById('star3').checked = true
    }

    return (

    <div className="rate">
        <input onClick={() => handleStarClick(5)} type="radio" id="star5" name="rate" value="5"/>
        <label htmlFor="star5" title="text">5 stars</label>
        <input onClick={() => handleStarClick(4)}  type="radio" id="star4" name="rate" value="4" />
        <label htmlFor="star4" title="text">4 stars</label>
        <input onClick={() => handleStarClick(3)}  type="radio" id="star3" name="rate" value="3" />
        <label htmlFor="star3" title="text">3 stars</label>
        <input onClick={() => handleStarClick(2)}  type="radio" id="star2" name="rate" value="2" />
        <label htmlFor="star2" title="text">2 stars</label>
        <input onClick={() => handleStarClick(1)}  type="radio" id="star1" name="rate" value="1" />
        <label htmlFor="star1" title="text">1 star</label>
    </div>
    )
}

I want the default behavior to have all the radio buttons unchecked.我希望默认行为取消选中所有单选按钮。 However, let's say in a form a user selects the 3-star radio button, I would like to be able to pass in a prop that allows me to render this component with the 3-star radio button checked.但是,假设在用户选择 3 星单选按钮的表单中,我希望能够传递一个道具,允许我在选中 3 星单选按钮的情况下呈现该组件。 What is the best way to go about this? go 的最佳方式是什么?

In React you shouldn't use document.getElementById() to access DOM elements.在 React 中,您不应该使用document.getElementById()来访问 DOM 元素。 It should be done using React Refs .它应该使用React Refs来完成。 In this case, you can avoid it.在这种情况下,您可以避免它。

You can use the following as a prop to make it work:您可以使用以下内容作为道具来使其工作:

checked={index === starClicked}

Your code can be simplified as below:您的代码可以简化如下:

 function Stars({ handleStarClick, starClicked }) { return ( <div className="rate"> {Array.from({ length: 5 }, (_, i) => { const index = 5 - i; return ( <React.Fragment key={index}> <input onChange={() => handleStarClick(index)} checked={index === starClicked} type="radio" id={`star${index}`} name="rate" value={index} /> <label htmlFor={`star${index}`} title="text"> {index} stars </label> </React.Fragment> ); })} </div> ); } function App() { const [starClicked, handleStarClick] = React.useState(-1); return <Stars handleStarClick={handleStarClick} starClicked={starClicked} />; } ReactDOM.render(<App />, document.querySelector('.react'));
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>

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

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