尝试根据用户选择显示元素

Trying to show element based on user selection

我的 div 包含两个选项 ["Book" , "prices"] 。 我的目标是当用户 select Book 选项时它会显示这本书的元素,价格也是一样。

这是我的代码:

const BooksandPrices = props => {
    const option =["Book" , "Prices"]
    return (
        <div>
                    {option.map((option) => (
                        <div
                            className='bp'
                            onClick={(e) => {
                                {option == 'Book' && <PriceTable  />}
                                {option == 'Prices' && <BookTable  />}
                            }}
                        >
                            {option}
                            </div>
                    ))}
        </div>
    )
}

return (

<BooksandPrices />

)

如果我的假设是正确的,并且是每个选项的元素,那么您需要将它们移出 option.map 并初始化一个状态变量来控制显示哪个元素

const BooksandPrices = props => {
    const [selectedOption, setSelectedOption] = useState();
    const option =["Book" , "Prices"]
    return (
        <div>
                    {option.map((option) => (
                        <div
                          className='bp'
                          onClick={() => setSelectedOption(option)}
                        >
                            {option}
                            </div>
                    ))}
                    {selectedOption == 'Book' && <PriceTable  />}
                    {selectedOption == 'Prices' && <BookTable  />}
        </div>
    )
}

return (

<BooksandPrices />

)

React Hooks 可以解决这个问题,你只需要添加 useState 钩子。 还请记住,在遍历数组时应该添加 key 属性。

const BooksandPrices = props => {
        const option =["Book" , "Prices"];
        const [checkedOption, setCheckedOption] = useState("Book");
        return (
            <div>
                        {option.map((option, idx) => (
                            <div
                                className='bp'
                                onClick={()=>setCheckedOption(option)}
                                key={idx}
                            >
                            {option}
                           
                     
                                   
      
                                </div>
                        ))}
                         <div>
                            {checkedOption === 'Book' ? <BookTable  />:<PriceTable /> }
                            </div>
            </div>
        )
    }