简体   繁体   中英

React - how to pass a prop into a class function call that is then accessed in componentDidMount function

I'm new to coding and have spent a long time trying to make this work but I am stuck. I know this is a very basic question and if it is answered elsewhere, I have failed to find the right questions to search to find that answer.

This is from the react tutorial -- it is the automatic timer that self-updates every 1000ms. I would like to be able to pass a prop into the <Clock /> function call to specify the interval I want that specific object instance to use like so: <Clock interval=2000 />

Here is the code they provided:

    function FormattedDate(props) {
      return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
    }

    class Clock extends React.Component {
      constructor(props) {
        super(props);
        this.state = {date: new Date()};
      }

      componentDidMount() {
        this.timerID = setInterval(
          () => this.tick(),
          1000
        );
      }

      componentWillUnmount() {
        clearInterval(this.timerID);
      }

      tick() {
        this.setState({
          date: new Date()
        });
      }

      render() {
        return (
          <div>
            <FormattedDate date={this.state.date} />
          </div>
        );
      }
    }

    function App() {
      return (
        <div>
          <Clock />
          <Clock />
          <Clock />
        </div>
      );
    }

    ReactDOM.render(<App />, document.getElementById('root'));

Here is what I have tried:

  • Setting the state to have timer: 5000
  • passing it in as a const to the function call
  • then updating the state in componentDidMount

However, this does not work because I am trying to use a prop to update state . What am I supposed to do instead?

Unsuccessful code: (just the bits I've tried)

        this.state = {
          date: new Date(),
          interval: 5000,
        };

    componentDidMount(props){
          () => this.tick(),
          props.timer
        );
      }

    const timer = {
      interval: 5000,
    }

    ReactDOM.render()
      <Clock interval={timer.interval}/>,
      document.getElementById('root')
    );

if you want to pass the interval as a prop you can do it like this:

   <Clock interval="1000"/>

and access it like this:


  componentDidMount() {
        this.timerID = setInterval(
          () => this.tick(),
         this.props.interval
        );
      }

You have to use this.props to have access to your props in the class components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM