gpt4 book ai didi

javascript - 解构纯函数组件中的 props

转载 作者:行者123 更新时间:2023-11-29 16:06:01 25 4
gpt4 key购买 nike

假设我们有以下纯函数:

const HeaderComponent = () => (
<h1> Title <h1>
)

export default HeaderComponent

现在我需要从 Prop 那里接收新的标题,所以我们经常解构this.props避免访问 titlethis.props.title在 render 方法中,我们将有类似的东西:

render() {
const {Title} = this.props;
return(
<h1> {Title} </h1>
)
}

问题是我们必须扩展 React.Component访问渲染方法的类。

是否可以在纯函数中使用解构?

const HeaderComponent = props => (
// const {Title} = this.props;
)

最佳答案

你可以这样做。我还发现这是一种使函数 self 记录的好方法。

const HeaderComponent = ({ title }) => (
<h1>{ title }<h1>
)

也可以设置默认值

const HeaderComponent = ({ title: 'Default Title' }) => (
<h1>{ title }<h1>
)

更新:作为T.J. Crowder指出, Title 在上面的示例中大写。在文本部分,它是小写的;按照惯例,我使用了小写版本

关于javascript - 解构纯函数组件中的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42113738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com