我想通过文件传输“状态”

时间:2018-11-02 21:01:40

标签: javascript html css reactjs

我有这样的代码:

class App extends Component {

        state = {
            active1: true,
            active2: false,
        }

        render() {
            if (this.state.active1) {

                <button onClick={() => {this.setState({ active1: false,
                                                        active2: true, })}
                />

            }

        }

我想将render()的这一部分放入另一个文件(例如Button.js),然后像这样将其导入此处:

class App extends Component {

        state = {
            active1: true,
            active2: false,
        }

        render() {
            if (this.state.active1) {
                return(
                    <Button />              // <== Here is the change
                )
            }

        }

我已经尝试过这样做,但是我认为我必须做出一些改变,因为当我这样做时,在React DevTool中,我看到当我单击按钮时,状态没有改变

1 个答案:

答案 0 :(得分:0)

您必须照顾自定义Button组件的所有道具。

您可以例如单击onClick组件中的button元素时,调用Button属性。

示例

// Button.js
import React from "react";

export default function Button(props) {
  return <button onClick={props.onClick}> Click me </button>;
}

// App.js
import React from "react";
import Button from "./Button.js";

class App extends React.Component {
  state = {
    active1: true,
    active2: false
  };

  render() {
    return (
      <div>
        <Button
          onClick={() => {
            this.setState({
              active1: false,
              active2: true
            });
          }}
        />
        {JSON.stringify(this.state)}
      </div>
    );
  }
}

function Button(props) {
  return <button onClick={props.onClick}> Click me </button>;
}

class App extends React.Component {
  state = {
    active1: true,
    active2: false
  };

  render() {
    return (
      <div>
        <Button
          onClick={() => {
            this.setState({
              active1: false,
              active2: true
            });
          }}
        />
        {JSON.stringify(this.state)}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>