Javascript 如何使用';数据-';道具传给了React类?
在我的调用JSX组件中给出了以下内容:Javascript 如何使用';数据-';道具传给了React类?,javascript,reactjs,react-jsx,Javascript,Reactjs,React Jsx,在我的调用JSX组件中给出了以下内容: 我希望能够在我的CoolThing类中使用这些字符串 class CoolThing extends Component { getStyle() { var itemx = this.props.data-itemx; var itemy = this.props.data-itemy; 这将生成NaN,而不是数据字符串。我尝试了其他一些方法: this.props.dataItemx // undefined
我希望能够在我的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
存在,但我无法访问它
我已经读过了,但仍然不清楚如何使这项工作
那么您是如何做到这一点的呢?使用
括号访问它符号,点符号不适用于-
class CoolThing extends Component {
getStyle() {
var itemx = this.props['data-itemx'];
var itemy = this.props['data-itemy'];
片段:
类CoolThing扩展React.Component{
render(){
log(this.props['data-itemx']);
返回(
你好,世界
)
}
}
ReactDOM.render(,document.getElementById('app'))代码>
Props
是一个对象,您通过键传递Props中的值:数据项x,数据项y
因此,这些值将以完全相同的名称提供,并使用括号[]
访问这些值。像这样:
class CoolThing extends Component {
getStyle() {
var itemx = this.props['data-itemx'];
var itemy = this.props['data-itemy'];
console.log(itemx, itemy);
....
建议:我建议您不要在属性名称中使用-,使用dataItemx
和dataItemy
而不是data itemx,data itemy
检查此代码段:
var-App=(道具)=>{
console.log(props['a-b'])
returnHello
}
ReactDOM.render(,document.getElementById('app'))