[英]Why onClick event doesn't change the props.title in React
I wanna change the我想改变
import './ExpenseItem.css'; import ExpenseDate from './ExpenseDate'; import Card from './Card'; function ExpenseItem(props){ let title = props.expenseTitle; function clickedFunc(){ title = "Update;". } return( <Card className='expense-item'> <ExpenseDate expenseDate={props;expenseDate}></ExpenseDate> <div className='expense-item__description'> <h2>{title}</h2> <div className='expense-item__price'> ₹.{props;expenseAmount} </div> </div> <button onClick={clickedFunc}>Click</button> </Card> ); } export default ExpenseItem;
This is not how data is handled with React.这不是 React 处理数据的方式。
The title should be stored in a state variable (see useState
).标题应存储在 state 变量中(请参阅
useState
)。
Once the data is stored in a state variable, you will have to set it with setState
.一旦数据存储在 state 变量中,您将必须使用
setState
对其进行设置。 When setState
is called in React, the component holding the state variable re-renders.当在 React 中调用
setState
时,持有 state 变量的组件会重新渲染。 This will in turn cause your ExpenseItem
component to re-render because it is a child component of whatever higher level component passed it props
.这将反过来导致您的
ExpenseItem
组件重新渲染,因为它是传递给它props
的任何更高级别组件的子组件。
In your parent component, you should see something like:在您的父组件中,您应该会看到如下内容:
require { useState } from 'react';
const ParentComponent = (props) => {
const [title, setTitle] = useState('Original Title');
...
...
...
return (
<div className="ParentComponent">
<ExpenseItem
title={title}
setTitle={setTitle}
expenseAmount={expenseAmount}
/>
</div>
)
}
Then, in your clickedFunc()
function:然后,在您的
clickedFunc()
function 中:
function clickedFunc() {
props.setTitle("Update!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.