我的ReactJS属性中有一个(可能是复杂的)JSON结构 - this.props.fieldsCollection . 我想在JavaScript函数中获取此对象,以便我可以遍历它并在React-Component中设置带有值的下拉列表 .
我无法在JS函数中获得值 .
function getPropertyValue() {
$(document).ready(function() {
var data = this.props.fieldsCollection; //gives "undefined"
});
}
我希望在“var data”中返回集合,以及迭代它的方法 . 我是Web开发人员的新手(所以请善待我的简单问题:)))
---------------------解决方案感谢您的回答---这是我的其他所做的-----------
它只是在ReactJS的render方法中设置全局JavaScript变量中的值 .
例如,
var fieldsCollection; // global JS variable
module.exports = React.createClass({
displayName: 'SidebarHeader',
render: function () {
return (
fieldsCollection = this.props.fieldsCollection, // setting the global variable value first when render is called
<div className="sidebar-header">
<div className="multi-select-field">
//incomplete React.createClass code …
function someJavaScriptFunction() {
var index, length = fieldsCollection.length;
for(index = 0; index<length; index++)
{
console.log(fieldsCollection.models[index].id); // testing code to iterate through the fieldsCollection ..
}
}
2 回答
您可以在全局范围上创建变量,然后在其中一个组件的事件中设置它的值 .
例如:
这里
varToRead
是您想要读取的变量 . 我们在getInitialState
上设置它的值,它作为组件事件的一个例子 .您可以看到我使用getInitialState示例的组件规范和生命周期:https://facebook.github.io/react/docs/component-specs.html
正在运行的示例如下:https://jsfiddle.net/c8x07p0s/
这是一个例子 .