简体   繁体   English

为什么 onClick 事件不会改变 React 中的 props.title

[英]Why onClick event doesn't change the props.title in React

I wanna change the我想改变

title标题

by clicking the button but it doesn't change, can I have an explanation why is that happens? 通过单击按钮但它没有改变,我可以解释为什么会这样吗?

 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'> &#8377.{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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM