将对象prop作为JSX属性而不是对象

时间:2017-03-02 19:36:30

标签: javascript json reactjs spread-syntax

给出以下组件。我正在寻找一种方法来获取这些道具,属性并将它们传递给这种格式的另一个组件。

<AdminHeader
  logoSource='https://dummyimage.com/85x85/c718de/ffffff'
  leftStyle={{flexGrow: 2}}
  centerText={'Painel De Administração · Clientes'}
  rightStyle={{flexBasis: 'content', flexGrow: 0}}
  right={(
    <AdminNotification
      imageSource='https://dummyimage.com/65x85/a8a8a8/000000.png'
      circleScheme='red'
      count={21}
      text='Admin Master'
    />
  )}
/>

例如,让我说我像这样包裹<AdminHeader/>

function WrappedAdminHeader (props) {
  return (
    <AdminHeader {...props.adminHeader}/>
  )
}

然后我想致电<WrappedAdminHeader />并传递adminHeader道具而无需将它们全部转换为JSON

<WrappedAdminHeader
  adminHeader={(
    <ResolveToJSON
      logoSource='https://dummyimage.com/85x85/c718de/ffffff'
      leftStyle={{flexGrow: 2}}
      centerText={'Painel De Administração · Clientes'}
      rightStyle={{flexBasis: 'content', flexGrow: 0}}
      right={(
        <AdminNotification
          imageSource='https://dummyimage.com/65x85/a8a8a8/000000.png'
          circleScheme='red'
          count={21}
          text='Admin Master'
        />
      )}
    />
  )}
/>

而不是像以下那样将属性转换为JSON:

<WrappedAdminHeader adminHeader={{
  logoSource: 'https://dummyimage.com/85x85/c718de/ffffff',
  leftStyle: {flexGrow: 2},
  centerText: 'Painel De Administração · Clientes',
  rightStyle: {flexBasis: 'content', flexGrow: 0},
  right:(
    <AdminNotification
      imageSource='https://dummyimage.com/65x85/a8a8a8/000000.png'
      circleScheme='red'
      count={21}
      text='Admin Master'
    />
  )}}
}>

这可能吗?

2 个答案:

答案 0 :(得分:0)

如果您的意思是希望<WrappedAdminHeader>的属性传递给<AdminHeader>,您可以直接在道具上使用属性传播:

function WrappedAdminHeader (props) {
  return (
    <AdminHeader {...props}/>
  )
}

现在,您可以使用<WrappedAdminHeader>作为<AdminHeader>的替代品:

<WrappedAdminHeader
  logoSource='https://dummyimage.com/85x85/c718de/ffffff'
  leftStyle={{flexGrow: 2}}
  centerText={'Painel De Administração · Clientes'}
  rightStyle={{flexBasis: 'content', flexGrow: 0}}
  right={(
    <AdminNotification
      imageSource='https://dummyimage.com/65x85/a8a8a8/000000.png'
      circleScheme='red'
      count={21}
      text='Admin Master'
    />
  )}
/>

答案 1 :(得分:0)

你的意思是这样的吗?

const A = ({ message }) => <span>{message}</span>;
const B = ({ propsForA }) => <A {...propsForA} />;

const a = <A message="Hi!" />;    

const App = () => (
  <div>{<B propsForA={a.props} />}</div>
);

ReactDOM.render(
  <App />,
  document.getElementById("entry")
);

你从a获取道具的地方是&#34;实例&#34; A