javascript - 在纯 ReactJS(功能)组件中渲染子 Prop

标签 javascript reactjs

React v0.14 支持 pure functional components (即相同的输入等于相同的输出)。 Prop 作为函数参数传入。

// Using ES6 arrow functions and an implicit return:
const PureComponent = ({url}) => (
  <div>
    <a href={url}>{url}</a>
  </div>
);

// Used like this:
<PureComponent url="http://www.google.ca" />

// Renders this:
<a href="http://www.google.ca">http://www.google.ca</a>

但是如何渲染 PureComponent 的子组件? 在常规有状态组件中,您可以使用 this.props.children 访问子组件,但这显然在这里不起作用。

const PureComponent = ({url}) => (
  <div>
    <a href={url}>{children}</a> // <--- This doesn't work
  </div>
);

<PureComponent url="http://www/google.ca">Google Canada</PureComponent>

// I want to render this:
<a href="http://www.google.ca">Google Canada</a>

我该怎么办?

最佳答案

您需要将 children 添加到参数“props”的解构赋值中。

const PureComponent = ({url, children}) => (...)

children 只是传递给组件的 Prop 。为了像使用 props.url 一样使用它,您需要将它添加到该列表中,以便它可以从 props 对象中“拉出”。

关于javascript - 在纯 ReactJS(功能)组件中渲染子 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35074013/

相关文章:

javascript - gentelella Angular 管理面板 - gentelella 切换菜单和侧边栏单击事件不起作用

javascript - Jest - 调用模拟函数不计算在内

javascript - 获取视频时长 jQuery

javascript - 在使用 redux 的 react 组件中访问 this.props 时未定义

javascript - 如何从 ReactJS 中的浏览器获取 URL 地址(服务器 URL)

javascript - 如何在 render() 中的 JSX 组件树中定义的组件上调用 React forceUpdate()

javascript - 使用 Electron 显示或读取操作系统或系统中存在的所有文件和文件夹

javascript - 从内部赋予 iframe 属性

javascript - "Error: You may not call store.getState() while the reducer is executing."

javascript - 通过路由 react 传递对象?