在react中处理一系列输入



我试图处理react中的一系列输入,这些输入由"查看;。地图";作用问题是我不能给字段一个特定的值。因此,我无法处理onChange函数中的输入。

我有卡片列表,每张卡片都会有一个管理员描述输入,每个按钮会发送不同的请求。

在这里,A制作了呈现卡片的功能。密码与输入有关

function createrequestcard(prop){
return(
<Card className="text-center" key={prop._id}>
<div class="wrapper">
<div id="requestspart1" class="left">
<Card.Body>
<Card.Title>Admin Description</Card.Title>
<Card.Text>
<textarea 
// --> Value of the index in aray
// --> Handle Change of input
/>
</Card.Text>
</Card.Body>
</div>
<div id="requestspart3" class="left">
<Card.Body>
<Card.Title>CREATE</Card.Title>
<Button variant="outline-success" className="AdminRequestButton">APPROVE</Button>   
<Button variant="outline-danger" className="AdminRequestButton">DENY</Button>
</Card.Body>
</div>
</div>
</Card>
)
}

在初始化类上的值时

this.state = {
requests: [],
description: '', 
}
}

请求aray从后端更新:

componentDidMount(){
this.checkloginstatus();
axios.get('http://localhost:3000/request', {withCredentials: true})
.then(resp => {
this.setState({requests: resp.data})
}).catch(err => console.log(err))
}

在渲染功能中:

<div>
{this.state.requests.map(createrequestcard)}
</div>

非常感谢你帮我。

您可以在map方法中传递索引,如下所示,

<div>
{this.state.requests.map((req,index) => createrequestcard(req, inex))}
</div>
function createrequestcard(prop, index){

map方法的结构如下

map((element) => { ... } )
map((element, index) => { ... } )
map((element, index, array) => { ... } )

您的卡组件应该定义如下,这里我将其命名为RequestCard(只是为了使其更可读(,当onchange事件发生在text区域。

function RequestCard(props){
return(
<Card className="text-center" key={prop._id}>
<div class="wrapper">
<div id={props.id} class="left">
<Card.Body>
<Card.Title>Admin Description</Card.Title>
<Card.Text>
<textarea  
onChange={(e)=>props.handleOnChange(e.target.value)}
// --> Value of the index in aray
// --> Handle Change of input
/>
</Card.Text>
</Card.Body>
</div>
<div id="requestspart3" class="left">
<Card.Body>
<Card.Title>CREATE</Card.Title>
<Button variant="outline-success" className="AdminRequestButton">APPROVE</Button>   
<Button variant="outline-danger" className="AdminRequestButton">DENY</Button>
</Card.Body>
</div>
</div>
</Card>
)}

现在你应该把它呈现为如下

<div>
{this.state.requests.map((request,index)=>{
return <RequestCard id={index} handleOnChange={(updatedValue)=>this.handleOnChange(index,updatedValue)}
})}

最后,您的句柄父组件的更改应该是这样的,

handleOnChange=(index,updatedValue)=>{
let curState=this.state;
curState.requests[index].value=updatedValue;//note that i am not aware what member of request you want to update
//so i assume value is the member of request object,you can change whatever you want
this.setState(curState);
}

最新更新