【问题标题】:Component communication - React JS组件通信 - React JS
【发布时间】:2019-02-09 04:41:02
【问题描述】:

如何从类外或 prop.SomeFunction () 进行状态更改? 我结合使用打字稿。是的,我已经上课了:

类:

import * as React from "react";
import { Label } from "../../components/label/label";
import { TextBox } from "../../components/textBox/textBox";
import IApp from "../../interfaces/global-interfaces";
import { myStyle } from "./style";

interface HeaderI {
    background: string;
    myFunc(): void;
    // elements: any[];
    // add(id: number, content: any, event: any): void;
}

interface HeaderStateI extends IApp.ElementI {
    background: string;
    elements: any[];
}

export class Header extends React.Component< HeaderI, HeaderStateI , any > {

    public myRef: React.RefObject<Label>;

    constructor(args: any) {
        super(args);
        this.state = { enabledComponent : true,
                       visibility: true,
                       debugView: false,
                       background: args.background,
                       elements: [],
                    };

        this.myRef = React.createRef();
        this.add = this.add.bind(this);

        console.log("state elements:" , this.state.elements);
    }

    public test() {
       alert("Y click on header element");
    }

    public printMe() {
      console.log("Layout Header is active :");
    }

    //  setText = (e: React.ChangeEvent) => {

      // this.setState ( { enabledComponent : true , background :  (e.target as HTMLInputElement).value } );

    // }

    public render() {

        if ( this.state.debugView === false ) {

            return (
                <div style={myStyle} onClick={this.addN} >
                <Label name="headerName" text="i am header paragraph!" />
                {this.state.elements.map((i: any) => {
                  return <span key={i} >{i}</span>;
                })}
                </div>
              );

        } else {

            this.printMe();

            return (
                <div style={myStyle} >
                <Label ref={this.myRef} name="headerName" text="i am header paragraph!"/>
                {this.state.elements.map((i: any) => {
                   return <li key={i} >{i}</li>;
                })}
                </div>
              );

        }

    }

    public componentDidUpdate(prevProps: any) {

        // Typical usage (don't forget to compare props):
        console.warn("prevProps name is: " + prevProps.name);
        if (this.props.background !== prevProps.background) {
          this.printMe();
        } else {
            console.log("Background is same no update.");
        }

    }

    public add = (id: number, content: any, event: any ) => {

        this.setState(
          {
            elements: [React.createElement("div", { key: 2 , onclick : null }, "tyest 12")],
            visibility : false,
          },
        );

        // tslint:disable-next-line:no-unused-expression
        console.log(" add from class in state elements,  visible is " , this.state.visibility );

    }

    public addN(event: MouseEvent | Event) {

        this.setState(
            {
              elements: [React.createElement("div", { key: 2 , onclick : null }, "tyest 12")],
              visibility : false,
            },
          );
        // tslint:disable-next-line:no-unused-expression
        console.log(" add from class in state elements,  visible is NNNN " , this.state.visibility );
    }

}

主文件:

const AddNewElement = Services.addNewElement;
const collectMe = <Header background="#127654"/>;

ReactDOM.render(
    <>
    {collectMe}
    <h3>Page title - inline text only example </h3>
     <Title name="title" text="Hello react title" />
     <Label name="root" text="I am text label component!"/> <br/>
     <TextBox name="root" text="I am textBox component!"/>
    </>,
    document.getElementById("root"),
);

//这个空间已经下课了,为什么我不能改变它???

collectMe.props.background = "#121212";
console.log(collectMe.props);

但是示例太纯了,没有传递参数等... 它只是一个商业膨胀项目的反应。

【问题讨论】:

  • 使用回调可以在react中修改父组件状态

标签: reactjs


【解决方案1】:

道具是read-only

无论你将组件声明为函数还是类,它都不能修改自己的 props。

你需要在这里做的是使用状态。要使用状态,您需要有基于类的组件。然后,您可以使用回调函数从子组件更新父组件状态。

看看这个post,从子组件更新父状态。

【讨论】:

  • "一个组件不能更新它自己的 props,除非它们是数组或对象(让一个组件更新它自己的 props,即使可能是一种反模式),但是可以更新它的 state 和它的 props孩子们。”我发现这个来自:stackoverflow.com/questions/24939623/…。 ....
  • 看起来构造函数中的每个右侧 var 都变成了只读的。我又修复了一个在构造函数中与状态无关的类属性。
猜你喜欢
  • 1970-01-01
  • 2021-02-02
  • 2017-09-12
  • 1970-01-01
  • 2017-04-07
  • 2015-09-18
  • 2017-11-08
  • 2020-10-16
  • 1970-01-01
相关资源
最近更新 更多