繁体   English   中英

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

[英]React: How to pass width as a prop from the component

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

喜欢:

<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;

我该如何实现?

您可以将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" />
        );
    }
}

如果您使用styled-componentsstyled-components ,则可以将width属性传递给组件并设置其宽度:

<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;

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

<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>
);
}

您可以同时以像素和百分比形式传递宽度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM