如何在React Js中更改Props值?

时间:2019-10-21 12:39:48

标签: reactjs react-redux setstate react-props

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

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

4 个答案:

答案 0 :(得分:1)

道具的反应不应更改,它们是val find : 'a -> 'a list -> 'a = <fun> 。在父组件中对其进行更新,然后将其作为新值传递。接收它们的组件应该只显示它​​们,并且逻辑处理应该在更高的级别上发生

答案 1 :(得分:0)

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

选项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}
  )
}

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

答案 2 :(得分:0)

您可以通过这样的不同组件来实现。

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;

答案 3 :(得分:0)

您不应该尝试直接在组件内部更新prop,但是您可以在该组件中触发一个事件,该事件将被父对象捕获,该事件会将该值作为prop传递给您的组件,然后父组件将更新该值如果接收到该数据作为道具的孩子,则将粘贴到所有对象。

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>
    }
}