gpt4 book ai didi

javascript - 在运行 mixin 代码之前 react : have component receive props or state, 或生成一个 id

转载 作者:行者123 更新时间:2023-11-30 10:04:50 25 4
gpt4 key购买 nike

在我的 React 组件中,我希望能够向 mixin 传递一个动态值,该值可以从组件的 props 或状态接收,也可以从组件在执行 mixin 之前运行的函数接收。这可能吗?

基本上,我想按照以下方式做一些事情:

/** @jsx React.DOM */
var React = require('react');
var MyMixin = require('./myMixin').MyMixin;

var Test = React.createClass({
mixins: [MyMixin.wantsToKnowTheTestId(this.props.id)],
propTypes: {
id: React.PropTypes.string.isRequired
},
render: function() {
return (<h1>My id is: {this.props.id}</h1>);
}
});

module.exports = {Test: Test};

当然,当我运行上面的代码时,我得到了Uncaught TypeError: Cannot read property 'id' of undefined since this.props is not defined yet when the mixin runs .

这或类似的事情是否可能?

最佳答案

您可以将 mixin 中的代码视为简单地复制到您的组件中,因此您的想法是行不通的。

根据您的 mixin 中的方法在做什么,您可以考虑在您的 mixin 中使用生命周期方法,该方法将在组件初始化后执行(因此一旦定义了 this.props)。

所以你的 mixin 看起来像

var MyMixin = {
wantsToKnowTheTestId: function(id) { ... },

componentDidMount: function() {
this.wantsToKnowTheTestId(this.props.id);
}

}

你的组件将简单地包含这个 mixin

/** @jsx React.DOM */
var React = require('react');
var MyMixin = require('./myMixin').MyMixin;

var Test = React.createClass({
mixins: [MyMixin],
propTypes: {
id: React.PropTypes.string.isRequired
},
render: function() {
return (<h1>My id is: {this.props.id}</h1>);
}
});

module.exports = {Test: Test};

关于javascript - 在运行 mixin 代码之前 react : have component receive props or state, 或生成一个 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29711000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com