如何更改 React Js 中的 Props 值?

How to Change Props value in React Js?

以下是下面的代码,现在我想在同一个组件中更改名称的值? 我该如何实现?

render(){
return(
<div>
<p>{this.props.name}</p>
</div>
)
}

props 不应在 React 中更改,它们是 readonly。在父组件中更新它们,然后将它们作为新值传递下去。接收它们的组件应该只是显示它们,逻辑处理应该发生在更高级别

您无法更改道具的价值,但您仍然可以选择更改您可以使用的价值。您有两个选择:要么从父组件更改它,要么使用 state 而不是 props。

选项 1/父更改:

const ParentComponent = props => {
  const [name, setName] = useState('')
  return (
    <div>
      <button onClick={() => setName('test')}>Test</button>
      <ChildComponent name={name} />
    </div>
  )
}

其中 ChildComponent 有您要使用的代码 this.props.name

选项 2/使用状态:

const MyComponent = props => {
  const [name, setName] = useState(props.name || '')
  return (
    {name}
  )
}

注意:这是未经测试的代码,用于显示想法,不可复制粘贴。

您可以像这样从不同的组件实现它。

App.js

import React from "react";
import ChildComponent from "./ChildComponent";

class App extends React.Component {
  state = {
    name: ""
  };
  handleChane = e => {
    this.setState({ name: e.target.value });
  };
  render() {
    const { name } = this.state;
    return (
      <div>
        <ChildComponent name={name} handleChane={this.handleChane} />
      </div>
    );
  }
}

ChildComponent.js

import React from "react";

function ChildComponent(props) {
  return (
    <div>
      <input
        type="text"
        onChange={props.handleChane}
        placeholder="enter your name"
      />
      {props.name}
    </div>
  );
}
export default ChildComponent;

您不应该尝试直接在您的组件内更新 props,但您可以在该组件中触发一个事件,该事件将被父组件捕获,该父组件将该值作为 props 传递给您的组件,然后父组件将更新该值将传递给所有接收该数据作为道具的 if child。

import { Component } from 'react';

class Child extends Component {
    render(){
        return(
            <div>
                <h2>{this.props.name}</h2>
                <button onClick={() => this.props.changeName("New name"); }>
                    Change Name
                </button>
            </div>
        )
    }
}

class Parent extends Component {
    constructor() {
        this.state = {
            name: "Name"
        }
    }
    handleChande (name) {
        this.setState({name: name});
    }

    render() {
        <div>
            <Child changeName={this.handleChange} />
        </div>
    }
}