使用属性初始化Reactjs组件

时间:2017-05-29 22:01:40

标签: reactjs

我想用一些ReactJS扩展我的经典HTML应用程序

我可以简化为:

<body>
  <my-component property="abc" />
  <my-component property="123" />
</body>

如何在React.Component中访问property的值?

1 个答案:

答案 0 :(得分:0)

我不知道我是否理解了您的问题,但如果您想要扩展某些HTML组件,则应使用扩展属性。 https://facebook.github.io/react/docs/jsx-in-depth.html#spread-attributes

自定义图像:

import React from 'react';
import ReactDOM from 'react-dom';

const MyImage = (props) => {
  // get your customized atribute
  const {log, alt, ...properties} = props;

  // Do wherever you want
  console.log(log);

  // Pass the rest to the image  
  return <img alt={alt} {...properties}/>;
};

ReactDOM.render(
  <MyImage log="logging action"
      alt="React logo"
      style={{ width: "400px", height: "400px"}}
      src="https://cdn.worldvectorlogo.com/logos/react.svg" />,
  document.getElementById('root')
);

注意:要了解alt属性未与其他属性一起传递的原因,请访问此链接https://github.com/evcohen/eslint-plugin-jsx-a11y/issues/7

相关问题