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

javascript - React: The best way to pass html attributes as props - Stack Overflow

programmeradmin1浏览0评论

For instance, I want to behave a Button as a normal button and enhance the ponent.

<Button type="submit" className="btn">Click me!</Button>

leads to an html element:

<button type="submit" className="btn">Click me!</button>

Is there a way to write the Button ponent like this?:

const Button = ({children, ...htmlAttributesOnly}) => (
    <button {...htmlAttributesOnly}>{children}</button>
)

The idea behind is to make a ponent as flexible as possible by giving access to all of its html elements' attributes. Or do I have to repeat every html element attribute?

For instance, I want to behave a Button as a normal button and enhance the ponent.

<Button type="submit" className="btn">Click me!</Button>

leads to an html element:

<button type="submit" className="btn">Click me!</button>

Is there a way to write the Button ponent like this?:

const Button = ({children, ...htmlAttributesOnly}) => (
    <button {...htmlAttributesOnly}>{children}</button>
)

The idea behind is to make a ponent as flexible as possible by giving access to all of its html elements' attributes. Or do I have to repeat every html element attribute?

Share Improve this question edited Oct 12, 2021 at 15:30 sebastianspiller asked Oct 12, 2021 at 15:00 sebastianspillersebastianspiller 801 silver badge4 bronze badges 1
  • 1 When you tried it did it work? – Andy Commented Oct 12, 2021 at 15:02
Add a ment  | 

2 Answers 2

Reset to default 8

You were really close to an answer, just wrap your props in curly braces:

const Button = ({ children, ...rest }) => (
    <button {...rest}>{children}</button>
)

You can create a Button ponent like this.

export default function Button(props) {
  return <button {...props}>{props.children}</button>;
}

Later you can use it like this.

  <Button onClick={()=>alert("hello")} style={{padding:10,border:'none',backgroundColor:'white'}} >Click Me</Button>
发布评论

评论列表(0)

  1. 暂无评论