[英]passing props to react component from standard html
so I wanted to do implement a sort of thing where I can put custom attributes in HTML elements which will be taken as props by a react component.所以我想实现一种我可以将自定义属性放在 HTML 元素中的东西,这些元素将被反应组件视为道具。 Something like:
就像是:
function someFunction(props) {
return <h1>props.something</h1>
}
HTML: HTML:
<div id="someElement" data-something="some text"></div>
renders:呈现:
<h1>some text</h1>
I THINK something like this could work, but I don't think its the best approach我认为这样的事情可行,但我认为这不是最好的方法
let render_div = document.getElementById("someElement")
render(<someElement something={render_div.getAttribute("data-something")}/>, render_div)
I'm new to react so please help me:)我是新手所以请帮助我:)
PS: I'm using typescript PS:我用的是typescript
Every data-
attribute you set on an HTML element is available inside the element.dataset
property.您在 HTML 元素上设置的每个
data-
属性都在element.dataset
属性中可用。 Keep in mind though that there's a naming conversion from dash-style to camelcase (see MDN ).请记住,虽然存在从破折号样式到驼峰式命名转换(请参阅MDN )。
What you should be able to do is something like the following:你应该能够做的是像下面这样的事情:
<div id="root" data-title="title" data-my-text="my-injected-text" />
import ReactDOM from 'react-dom';
import App from './App';
const rootNode = document.getElementById('root');
const props = element.dataset; // { title: 'title', myText: 'my-injected-text' }
ReactDOM.render(App, props, rootNode);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.