【问题标题】:Edit an Item in a list编辑列表中的项目
【发布时间】:2020-03-29 11:51:59
【问题描述】:

我正在使用 react js 和语义 UI 库创建一个待办事项应用程序。

虽然添加和删除功能运行良好,但我仍坚持使用编辑功能。以下是代码sn-ps。

App.js

class App extends Component{
  constructor(props){
    super(props);

    this.state={
        item :'',

        listItems:[

        ],

    }

    this.handleChangeItem = this.handleChangeItem.bind(this);

  }

updateItem=(key,item)=>{
    const newlistItems = [...this.state.listItems]
    newlistItems.map(list=>{
      if(list.key===key){
        list.item = item;
      }
    }
      )

      this.setState({
        listItems:newlistItems
      })
  }

ListView.js

 <List.Content>

                     { 
                     this.props.listItems.map((item, index) => <List.Header key={index}   > 
                        <span>
                            <input 
                            size="50%"
                             id={index}
                             value={item} 
                             onChange={(event)=>{this.props.updateItem(event.target.value,index)}}
                             />
 </List.Content>

我正在父组件中实现编辑功能,并在列表视图组件的输入字段中为onChange 方法调用它。我无法在视图组件中编辑输入字段的值。

谁能帮我解决这个问题?

【问题讨论】:

    标签: javascript arrays reactjs semantic-ui-react


    【解决方案1】:

    问题在于您的updateItem 函数。你可以使用setState 和回调来访问你之前的状态。

    尝试以下方法:

    updateItem = (key, item) => {
        this.setState(prevState => {
           ...prevState,
           listItems: prevState.listItems.map(list => {
              if(list.key === key){
                 list.item = item;
              }
    
              return list;
           })
        })
    }
    

    也许在您的onChange 事件中您想通过item 而不是index

    onChange={ event => { this.props.updateItem(event.target.value, item) } }
    

    我希望这会有所帮助!

    【讨论】:

    • 我只想在输入字段中移动光标。但我做不到。你能帮我解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 2021-12-25
    相关资源
    最近更新 更多