最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React: How to pass width as a prop from the component - Stack Overflow

programmeradmin1浏览0评论

I am trying to create a component, whose width can be specified wherever the component can be used

Like:

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

how can I achieve this?

I am trying to create a component, whose width can be specified wherever the component can be used

Like:

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

how can I achieve this?

Share Improve this question asked Dec 8, 2017 at 15:44 userNotHereuserNotHere 971 gold badge2 silver badges11 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 7

You can pass width as props to button component like,

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

In your main component import your button and work as what you want like below

import Button from 'your_button_component_path';

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

You can pass it as props in this way

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

And create Button component.

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

You can pass width in both pixel and percentage.

If you're using styled-components you can pass the width prop to the component and set its 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;
发布评论

评论列表(0)

  1. 暂无评论