我想知道如何使用React.js编写执行以下操作的代码 我草绘了一个JQuery示例来演示我想要的东西:
let form = " <form class='update-name'> <input type='text' class='room-new-name'> <input type='submit'> </form>"
$(".room-name").on("click",function(){
let parent = $(this).parent()
parent.append(form)
})
$(".room").on("submit",function(event){
event.preventDefault()
let newName = $(".room-new-name").val()
$(".room-name").text(newName)
$(".room > .update-name").remove()
})
反应代码...。(不完全确定如何使用react来思考这个问题)
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
rooms:[{name:"coffee talk"},{name:"cooking"},{name:"skateboarding"},{name:"coding"}]
}
}
changeName(){
// ?
}
render() {
let roomList = this.state.rooms.map((val,index)=>{
return <li key={index}>{val.name}</li>
})
return (
<div>
<ul>
{roomList}
</ul>
</div>
);
}
}
ReactDOM.render(
<div>
<App/>
</div>,
document.getElementById('root')
)
答案 0 :(得分:1)
我想我已经弄清楚了,但是我不确定这是“最佳实践”还是接近。
http://jsfiddle.net/od6ces0a/1/
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
rooms:[{name:"coffee talk"},{name:"cooking"},{name:"skateboarding"},{name:"coding"}],
roomCSS:{display:"none"},
selectedRoomIndex:undefined,
tempName:"",
}
}
setRoomIndex=(roomID)=>{
console.log(roomID);
this.setState({
selectedRoomIndex:roomID,
roomCSS:{display:"block"}
})
}
handleChange=(event)=> {
this.setState({tempName: event.target.value});
}
setNewRoomName=(event)=>{
event.preventDefault()
let updatedRoomList = this.state.rooms.map((val,index)=>{
if(index === this.state.selectedRoomIndex){
val.name = this.state.tempName;
return val
}else{
return val
}
})
this.setState({
rooms:updatedRoomList,
roomCSS:{display:"none"},
tempName:""
})
}
render() {
let roomList = this.state.rooms.map((val,index)=>{
return <li onClick = {()=>this.setRoomIndex(index)} key={index}>
<span>{val.name}</span>
</li>
});
return (
<div>
<ul>
<form onSubmit={this.setNewRoomName} className="change-room-name" style={this.state.roomCSS}>
<input type="text" onChange = {this. handleChange} value={this.state.tempName}/>
<input type="submit"/>
</form>
{roomList}
</ul>
</div>
);
}
}
ReactDOM.render(
<div>
<App/>
</div>,
document.getElementById('root')
)