Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在react.js中获取动态创建的组件的值?_Reactjs - Fatal编程技术网

Reactjs 如何在react.js中获取动态创建的组件的值?

Reactjs 如何在react.js中获取动态创建的组件的值?,reactjs,Reactjs,我在获取动态生成组件的值时遇到问题。我能够以子组件为目标。但是,我无法获取子组件的值。不知道我错过了什么。由于我使用的是数组对象(使用Firebase作为数据库),所以设置有点有线。小提琴: //Javascript jsx 风险值数据={ a:'全部', b:‘球’, c:‘猫’ }; var mycop=React.createClass({ getInitialState:函数(){ 返回{ 数据:this.props.data }; }, handleClick:函数(e){ conso

我在获取动态生成组件的值时遇到问题。我能够以子组件为目标。但是,我无法获取子组件的值。不知道我错过了什么。由于我使用的是数组对象(使用Firebase作为数据库),所以设置有点有线。小提琴:

//Javascript jsx
风险值数据={
a:'全部',
b:‘球’,
c:‘猫’
};
var mycop=React.createClass({
getInitialState:函数(){
返回{
数据:this.props.data
};
},
handleClick:函数(e){
console.log(如target);
console.log(例如target.value)
},
render:function(){
var o=this.props.data;
返回(
{Object.keys(o).map(函数(k){
返回(
{o[k]}
);
}.bind(this))}
);
}
});
React.render(,document.getElementById('container');

首先-删除内部
{o[k]}
前后的空格。查看生成的标记,有三个
span
元素,您正在尝试获取单击的span的
值。第二,我建议使用
getAttribute
方法获取属性值。我修改了你的小提琴-

handleClick:函数(e){
console.log(如target);
log(e.target.getAttribute('data-value');
}
//...
{o[k]}

非常感谢您提供的解决方案。并指出了扩展空间。我没能弄明白为什么我会有跨距!!!
// Javascript jsx
<script type="text/jsx">
     var data = {
        a: 'all',
        b: 'ball',
        c: 'cat'
    };



var MyComp = React.createClass({

getInitialState: function(){
    return{
        data: this.props.data
    };
},

handleClick: function(e){
    console.log(e.target);
    console.log(e.target.value)
},


render: function() {
    var o = this.props.data;

    return(
        <div className="words">
            {Object.keys(o).map(function(k) {
                return (
                    <div key={k} className="word" onClick={this.handleClick} value={o[k]}> {o[k]} </div>
                );
            }.bind(this))}
        </div>

    );
}
});



React.render(<MyComp data={data} /> , document.getElementById('container'));


</script>
handleClick: function(e){
        console.log(e.target);
        console.log(e.target.getAttribute('data-value'));
}
//...
<div key={k} className="word" onClick={this.handleClick} data-value={o[k]}>{o[k]}</div>