猿问

如何将单击项目的索引移动到不是父项的另一个组件?

预期效果:点击<li>--> 获取索引 --> 将此索引发送到组件Watch。当我单击 时<li>,我抓取索引并将其移动到Watch组件。但是,当我单击第二个时,li它会返回我第一次单击的索引。我认为这是因为它通过componentDidMount. 之后如何引用此索引componentDidMount?


去做


class Todo extends Component {

      render () {

        return (

          <div className = "itemTodos" onClick={()=> this.props.selectTodo(this.props.index)}>

          </div>

        )

      } 

    }


    export default Todo;

应用程序


class App extends Component {

  constructor(){

    super();


    this.state {

      selectedTodoIndex: index

    }


  }


  selectTodo = (index) => {

    this.setState({

      selectedTodoIndex: index

    })

  }


  render () {

    return (

      <div>

           <ul>

      {

        this.state.todos

          .map((todo, index) =>

            <Todo

              key={index}

              index={index}

              todo={todo}

              selectTodo ={this.selectTodo}

            />

          )

      }

    </ul>

          <Watch

            selectedTodoIndex = {selectedTodoIndex}

          />

      </div>

    )

  } 

}


export default App;

手表


class Watch extends Component {

  constructor(){

    super();


    this.state = {

      selectIndex: null

    }

  }


 componentDidMount() {

    this.setState({

      selectIndex:  this.props.selectedTodo

    });

 }



  render () {

    return (

      <div>

      </div>

    )

  } 

}


狐的传说
浏览 118回答 3
3回答

小怪兽爱吃肉

如果我没有错,你的 Todo 组件正在监视中??。所以Watch组件应该是这样的:render () {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp;<Todo index={this.state.selectedIndex} selectedTodo={this.props.selectedTodoIndex}/>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )&nbsp; }&nbsp;在这里,我制作了这段代码的代码和盒子。请随时结帐,如果您有任何疑问,请告诉我。代码链接:https : //codesandbox.io/s/frosty-chaplygin-ws1zz

慕桂英4014372

有很多改进要做。但我相信您正在寻找的是Watch Component 中的getDerivedStateFromProps lifeCycle 方法。所以代码将是:getDerivedStateFromProps(nextProps, prevState) {&nbsp; if(nextProps.selectedTodoIndex !== prevState.selectedTodoIndex) {&nbsp; &nbsp; return { selectIndex: nextProps.selectedTodoIndex }&nbsp; }}这将检查 App 组件中选定的索引是否已更改,如果是,它将更新 Watch 组件中的状态。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答