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" />
);
}
}
你可以通过这种方式将它作为道具传递
<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>
);
}
您可以以像素和百分比的形式传递宽度。
如果您使用 styled-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%" />
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" />
);
}
}
你可以通过这种方式将它作为道具传递
<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>
);
}
您可以以像素和百分比的形式传递宽度。
如果您使用 styled-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;