React:如何从组件传递宽度作为prop

时间:2017-12-08 15:44:05

标签: javascript reactjs styled-components

我正在尝试创建一个组件,可以在组件可以使用的任何地方指定其宽度

喜欢:

<Button label="button" width="80%" />

const TestButton = styled.button`
  color: red;
`;

var React = require('react');

var Button = React.createClass({

render: function () {

return (
  <TestButton>{this.props.label}</TestButton>
);
}
});

module.exports = Button;

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:4)

您可以将width作为道具传递给按钮组件,例如

export const Button = (props) => { // Your button component in somewhere
    return (
        <button style={{width: `${props.width}`}}>{props.label}</button>
    )
}

在您的主要组件import中按下按钮并按照下面的工作

import Button from 'your_button_component_path';

class RenderButton extends React.Component {
    render() {
        return (
            <Button width="80%" label="Save" />
        );
    }
}

答案 1 :(得分:4)

如果你正在使用styled-components,你可以将宽度道具传递给组件并设置其宽度:

<Button label="button" width="80%" />

const TestButton = styled.button`
  color: red;
  width: ${(props) => props.width}
`;

var React = require('react');

var Button = React.createClass({

  render: function () {

    return (
      <TestButton width={this.props.width}>{this.props.label}</TestButton>
     );
    }
  });

module.exports = Button;

答案 2 :(得分:3)

您可以通过这种方式将其作为道具传递

<Button label="button" width="80%"/>

并创建Button组件。

export const Button = (props) => {
return(
    <button
    style={{width: props.width}}   // or you can pass whole style object here
     >
    {props.label}
    </button>
);
}

您可以按像素和百分比传递宽度。