假设我们有以下纯函数:
const HeaderComponent = () => (
<h1> Title <h1>
)
export default HeaderComponent
现在我需要从 Prop 那里接收新的标题,所以我们经常解构this.props
避免访问 title
与 this.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/