在我调用的 JSX 组件中给出以下内容:
<CoolThing data-itemx="Corduroy" data-itemy="Pancakes" />
我希望能够在我的 CoolThing
中使用这些字符串类。
class CoolThing extends Component {
getStyle() {
var itemx = this.props.data-itemx;
var itemy = this.props.data-itemy;
这会产生 NaN
而不是数据字符串。我尝试了一些其他的东西:
this.props.dataItemx // undefined
this.props.dataitemx // undefined
this.props.itemx // undefined
this.props.data.itemx // error accessing itemx of undefined
正在运行 console.log(this.props)
表明 data-itemx
存在,但我无法访问它。
我已经阅读了 https://facebook.github.io/react/docs/dom-elements.html但目前还不清楚如何进行这项工作。
那么你是怎么做到的呢?
最佳答案
使用brackets
表示法访问它,点表示法不适用于-
class CoolThing extends Component {
getStyle() {
var itemx = this.props['data-itemx'];
var itemy = this.props['data-itemy'];
片段:
class CoolThing extends React.Component {
render() {
console.log(this.props['data-itemx']);
return (
<div>Hello World</div>
)
}
}
ReactDOM.render(<CoolThing data-itemx="4324"/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
关于javascript - 如何使用传递给 React 类的 'data-' Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44126176/