我一直在尝试将数据从表格中获取到ReactJS中的模态,尝试以最小的努力使其工作。我想我理解组件如何工作正常。但是当在模态中显示数据时,我希望组件首先遍历列表并删除其余行上的“选定”类,然后显示所选行。现在我的模态只显示最后一行,无论我在哪里点击。
var BoatRow = React.createClass({displayName: 'BoatRow',
handleClick: function(event){
this.setState({className:'selected'});
},
getInitialState: function(){
return (
{
className:'!selected',
}
)
},
render:function(){
var listed = this.state.className ? 'selected' :
localStorage.setItem('boat', JSON.stringify({
name:this.props.boat.Name,
//some data
}));
return (
React.DOM.tr({className:this.state.className},
React.DOM.td(null, this.props.boat.Name),
//rest of table row data
React.DOM.button({type: "button", 'data-toggle': "modal", 'data-target': "#modalContent", onClick:this.handleClick
}, "Select" )
)
)
)
}
});
我首先浏览JSON对象并将其推送到数组。
var AllBoatList = React.createClass({displayName: 'AllBoatList',
render: function(){
var rows = [];
var lastAvailable = null;
this.props.boats.forEach(function(boat, i){
if(boat.Availability !== 0){
rows.push(BoatRow({boat:boat, key:boat.id}));
}
});
return(
React.DOM.table({id:"boat-table"},
//table head
)
),
React.DOM.tbody(null, rows)
)
);
}
});
var data = [{
"Name": "Boat Name",
"id": "1"
}, //rest of Json data
}
]
React.render(AllBoatList({boats:data}),
document.getElementById('all-boats')
);
这就是模态数据的显示位置。
var Boats = require(['./assets/src/scripts/boats']);
var BoatModal = React.createClass({displayName: 'BoatModal',
getInitialState: function(){
return {
value: JSON.parse(localStorage.getItem('boat'))
}
console.log(this.state.value);
},
render:function(){
return (
React.DOM.div({className: "DisplayContainer"},
React.DOM.p(null,
this.state.value
)
)
)
}
});
React.render(BoatModal({}), document.getElementById('modal-body')
);
组件工作正常,显示表并选择正确的行,更改类。我只是遇到问题,模态上显示的数据不是我的选择,但总是最后一行。我该如何解决这个问题?
答案 0 :(得分:0)
我终于有了它的工作。我不知道我是否完全理解这一点,但我必须将所有onClick事件移动到事件处理程序。 Modal使用正确的数据进行此更改
var BoatRow = React.createClass({displayName: 'BoatRow',
handleClick: function(event){
this.setState({className:'selected'});
//this is where storage should happen
localStorage.setItem('boat', JSON.stringify({
"Name":this.props.boat.Name
//adding this line fixed it
})).bind(this.props.boat.Name);
console.log("storage written");
},
getInitialState: function(){
return (
{
className:'!selected'
}
)
},
render:function(){
var listed = this.state.className ? '!selected' : 'selected'
...