简体   繁体   English

ReactJS 从 onClick 函数更改 JSX

[英]ReactJS Change the JSX from onClick function

i have a backend api build on nodejs.我在 nodejs 上构建了一个后端 api。 in the code the api return some categories array.在代码中,api 返回一些类别数组。 i ran .map() function on the array to display the array in the JSX.我在数组上运行 .map() 函数以在 JSX 中显示数组。 after that i added a checkBox to each object inside the array.之后,我向数组内的每个对象添加了一个复选框。

so what im trying to do is if the checkbox is true its will added another h1 Element (JSX).所以我想要做的是,如果复选框为真,它将添加另一个 h1 元素(JSX)。 Only to the object i clicked on the checkbox.仅针对我单击复选框的对象。

i tryied to add "status" props and make it false or true and then catch it with onClick e.target.status?我尝试添加“状态”道具并使其为假或真,然后使用 onClick e.target.status 捕获它? "YES" : "NO" “是”:“否”

also, i tried to added checkBox useState and make it true or false .另外,我尝试添加 checkBox useState 并使其 true 或 false 。 and its work.和它的工作。 but not as i want its display Yes or No to the all objects and not only to the on i clicked on.但不是因为我希望它对所有对象显示是或否,而不仅仅是我单击的对象。

const Category = ({ history }) => {
const dispatch = useDispatch()
const user = useSelector((state) => state.waiter)
const selectedCategory = useSelector((state) => state.selectedTable)

const [currectCategory, setCurrectCategory] = useState([])
const [categoryName, setCategoryName] = useState("")
const [categoryIMG, setCategoryIMG] = useState("not found")

const [checkBox, setCheckBox] = useState("false")

useEffect(() => {
    if (!user.name) {
        history.push('/login')
    } else {
        (async () => {
            const res = await fetch('http://localhost:1000/categories/' + selectedCategory)
            const data = await res.json()
            setCurrectCategory(data.CurrectCountry.subcategories.map(sc => sc.name))
            setCategoryName(data.CurrectCountry.name)
            setCategoryIMG(data.CurrectCountry.img)
        })()
    }
}, [user])

const goBack = () => {
    dispatch({
        type: 'ALL_CATEGORIES'
    })
    history.push('/login')
}

const handleCheck = (e) => {
    setCheckBox(e.target.checked.toString())
    console.log(e.target.checked)

}
return (
    <>
        <Button className="LogButton" color="secondary" onClick={goBack}>back</Button>
        <div className="SingleCategory">
            <h1>{categoryName}</h1>
            <ListGroup>
                {currectCategory.map(category => {
                    return (
                        <Row className="Col-padd" key={category}>
                            <div>
                                <InputGroup className="mb-3">
                                    <b className="ItemName"> {category} </b>
                                    <img src={categoryIMG} height="100" width="100" ></img>
                                    <FormCheck id={category} className="Checkbox" onChange={handleCheck}></FormCheck>
                                    {checkBox == "true" ? <b>yes</b> : <b>No</b>}
                                </InputGroup>
                            </div>
                        </Row>
                    )
                })}
            </ListGroup>
        </div>
    </>
)

} }

Thanks for help !!感谢帮助 !!

You are only creating a single value for the checkbox.您只是为复选框创建了一个值。 If you want to show for all the checkbox, if you have to track the value for each checkbox shown below,如果要显示所有复选框,如果必须跟踪下面显示的每个复选框的值,

const [checkBox, setCheckBox] = useState({}); // checkBoxName: value



 const handleCheck = (e) => {
    setCheckBox((prev) => {...prev, [e.target.name]: e.target.value};
   }


 {!!checkBox['name'] === true ? <b>yes</b> : <b>No</b>} 
//change the attribute according to your implementation.

Your problem is that you're just creating a single value for the checkbox and not separating the individual checkboxes.您的问题是您只是为复选框创建了一个值,而不是将各个复选框分开。 You could solve this in many different ways, but you would be well served by extracting the code for your checkbox to a separate component.您可以通过许多不同的方式解决这个问题,但是通过将复选框的代码提取到一个单独的组件中,您会得到很好的服务。

const Checkbox = ({ category, categoryIMG }) => {
  const [isChecked, setIsChecked] = useState(false);

  const handleCheck = () => {
    setIsChecked((prevState) => !prevState);
  };

  return (
    <Row className="Col-padd" key={category}>
      <div>
        <InputGroup className="mb-3">
          <b className="ItemName"> {category} </b>
          <img src={categoryIMG} height="100" width="100"></img>
          <FormCheck id={category} className="Checkbox" onChange={handleCheck}></FormCheck>
          {isChecked == 'true' ? <b>yes</b> : <b>No</b>}
        </InputGroup>
      </div>
    </Row>
  );
};

With a separate checkbox component like above you could instantiate it like this in the map:使用像上面这样的单独复选框组件,您可以在地图中像这样实例化它:

<ListGroup>
    {currectCategory.map((category) => (
        <Checkbox category={category} categoryIMG={categoryIMG} />
    ))}
</ListGroup>

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

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