How to change the value of props in react?

In React, props are read-only and cannot be directly modified. However, the value of props can be changed by the parent component.

  1. Define a state in the parent component to store the props value that needs to be modified.
  2. Define a function in the parent component to modify the value in the state.
  3. Pass the modified value to the child component through props.
  4. Render using props passed from the parent component in the child component.

Here is an example:

// 父组件
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const [propValue, setPropValue] = useState('initial value');

  const handleButtonClick = () => {
    // 修改propValue的值
    setPropValue('new value');
  };

  return (
    <div>
      <ChildComponent propValue={propValue} />
      <button onClick={handleButtonClick}>修改props的值</button>
    </div>
  );
}

export default ParentComponent;

// 子组件
import React from 'react';

function ChildComponent(props) {
  return <div>{props.propValue}</div>;
}

export default ChildComponent;

In the example above, a statepropValue is defined in the parent component ParentComponent to store the props value that needs to be modified. The parent component also defines a function handleButtonClick that is called when the button is clicked, which modifies the value of propValue. The modified value is then passed to the child component ChildComponent through props for rendering.

When the button is clicked, the props value in the child component will be updated, triggering a re-render of the child component to display the modified value.

bannerAds