设置一个单选按钮要检查为默认值
假设我在React中具有这样的函数,
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>
)
}
我希望默认行为未选中所有无线电按钮。但是,假设用户选择三星级广播按钮,我希望能够传递一个使我可以通过检查的三星级广播按钮来渲染该组件的道具。最好的方法是什么?
Suppose I have a function like this in React
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. What is the best way to go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在React中,您不应使用
document.getElementById()
访问DOM元素。应该使用 react ref refs refs 进行完成。在这种情况下,您可以避免它。您可以将以下内容用作使其正常工作的道具:
您的代码可以如下简化:
In React you shouldn't use
document.getElementById()
to access DOM elements. It should be done using React Refs. In this case, you can avoid it.You can use the following as a prop to make it work:
Your code can be simplified as below: