尝试在组件之间传递数据时未定义
问题描述:
首先,我是React中的新成员。我有两个组件TagUtils
和Urls
。我试图将路由器参数从Urls
传递到TagUtils
。这里是我的代码:尝试在组件之间传递数据时未定义
Urls.jsx
// some codes....
export default class Urls extends React.Component {
render() {
return (
<div>
<TagUtils tag={this.props.params.tag_id}/>
</div>
)
}
}
TagUtils.jsx
export default class TagUtils extends React.Component {
deleteTag(props) {
console.log(props.tag);
}
render() {
return (
<div className="col-xs-6 col-md-4">
<button type="button" className="btn btn-danger" onClick={this.deleteTag}><i className="fa fa-trash"> Delete</i></button>
</div>
)
}
}
当我点击删除按钮,它只是显示undefined
。也许我失去了一些东西。
答
随着React从createClass转移到ES6 classes
,我们需要对我们自己的方法处理正确的值this
,如下所述:http://www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classes 更改您的代码有界纠正构造的该值的方法:
export default class TagUtils extends React.Component {
constructor(props) {
super(props);
this.deleteTag = this.deleteTag.bind(this);
}
deleteTag(props) {
console.log(props.tag);
}
render() {
return (
<div className="col-xs-6 col-md-4">
<button type="button" className="btn btn-danger" onClick={this.deleteTag}><i className="fa fa-trash"> Delete</i></button>
</div>
)
}
}
的no autobinding
来自阵营家伙ES6类从容不迫的步伐。自动绑定纠正上下文提供了React.createClass
。这个细节可以在这里找到:https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding
所以在此基础上,你也可以改变你的代码:
export default class TagUtils extends React.Component {
deleteTag = (props) => {
console.log(props.tag);
}
render() {
return (
<div className="col-xs-6 col-md-4">
<button type="button" className="btn btn-danger" onClick={this.deleteTag}><i className="fa fa-trash"> Delete</i></button>
</div>
)
}
}
答
在您的例子props
是event
对象不存在tag
财产 - 这就是为什么你得到undefined
,则需要设置this
为deleteTag
,然后你可以通过this.props
进去deleteTag
方法分量props
export default class TagUtils extends React.Component {
constructor() {
this.deleteTag = this.deleteTag.bind(this);
}
deleteTag() {
console.log(this.props.tag);
}
render() {
return (
<div className="col-xs-6 col-md-4">
<button type="button" className="btn btn-danger" onClick={this.deleteTag}>
<i className="fa fa-trash"> Delete</i>
</button>
</div>
)
}
}
你可以在控制台中看到this.props.params.tag_id如果您登录了吗?您应该使用this.props.tag_id,并且您需要在某处设置tag_Id,我们是否可以看到该代码? – JordanHendrix
反应es6类文档:https://facebook.github.io/react/docs/reusable-components.html#es6-classes – JordanHendrix