我在学习 React 时感到非常困惑。 例如,我有一个非常简单的 React 组件:
export default function Foo(){
return(
<div>
<div>some text</div>
</div>
)
}
我想要添加一个子组件:
export default function Foo(){
const Bar = ()=>{
return (
<input placeholder="some input"/>
)
}
return(
<div>
<div>some text</div>
</div>
)
}
据我所知,我可以以两种方式使用此组件:
1. 作为函数使用
return(
<div>
<div>some text</div>
{Bar()}
</div>
)
2. 作为组件使用:
return(
<div>
<div>some text</div>
<Bar/>
</div>
)
这两者有何不同?我以前认为它们是一样的,直到我在输入框中使用组件
<Bar/>
时遇到了问题,即在我输入第一个字母后,输入框会失去焦点。演示如下:https://codesandbox.io/s/gifted-archimedes-l7bce7?file=/src/App.js 那么这里确切的问题是什么?我一直将其编码为组件,根据我的理解,当它返回React组件时,
<Bar/>
与Bar()
相同。我是对还是错?
编辑:我找到了这篇博客,它非常接近这个问题,并且也很棒 :) https://dev.to/igor_bykov/react-calling-functional-components-as-functions-1d3l?signin=true