在react 中引入js
Today I wrote a simple tabbed show and hide feature in React.JS. There are components for previews, and then a component showing more details of the item that is active.
今天,我在React.JS中编写了一个简单的选项卡式显示和隐藏功能。 有用于预览的组件,然后是用于显示活动项目的更多详细信息的组件。
It starts off with nothing active, so the state is initially set as null.
它开始时没有任何活动,因此状态最初设置为null 。
const [activeItem, setActiveItem] = useState(null);const handleClick = (itemIndex) => { setActiveItem(itemIndex); };A handleClick event is passed through to the preview components so that they can set themselves as the active item.
handleClick事件将传递到预览组件,以便它们可以将自己设置为活动项目。
<ItemHeader data={ item } index={ index } onClick={ handleClick } active={ index === activeItem }/>When the preview is clicked, it sets itself as the active item, using the index and handler that have been passed in from the parent.
单击预览时,它使用从父级传入的索引和处理程序将自身设置为活动项。
<div onClick={ () => props.onClick(props.index) }>If one of the items is active, a FullItem component is rendered.
如果其中一项处于活动状态,则会呈现FullItem组件。
{ activeItem && ( <FullItem data={ props.items[activeItem] } /> )}I got this far and thought: great. I am a genius and a professional with many skills. But I had forgotten something.
我想到了这一点:太棒了。 我是一个天才,而且拥有很多技能。 但是我忘记了一些东西。
You see, I more frequently program with Ruby, where I would always expect the index of an array to be truthy:
您会发现,我更经常使用Ruby编程,在此我总是希望数组的索引是真实的:
➜ ~ irbirb(main):001:0> 0 && "a"=> "a"irb(main):002:0> nil && "a"=> nilBut this is Javascript:
但这是Javascript:
➜ ~ nodeWelcome to Node.js v12.18.0.Type ".help" for more information.> 0 && "a"0> null && "a"nullSo it needs to be more specific.
因此,它需要更具体。
{ (activeItem !== null) && ( <FullItem data={ props.items[activeItem] } /> )}What catches you out when switching between programming languages?
在编程语言之间切换时,有什么吸引您?
翻译自: https://medium.com/@merxplat/discovering-the-nature-of-truth-in-react-js-34b194ff6fb4
在react 中引入js