[英]Show/Hide elements in reactJS
我第一次使用 React.js,找不到方法来显示或隐藏新输入字段来代替我的 label。 我搞砸了一点,但最后我卡住并删除了editItem代码,这是我到目前为止的代码,我不知道如何继续/创建editItem function。 有什么建议吗?
import React, {Component} from "react";
import {v4 as uuidv4} from 'uuid';
import "./App.css";
class App extends Component {
state = {
todos: [],
};
handleInputValue = (event) => {
console.log('-------handleinputvalue');
this.setState({inputValue: event.target.value, id: uuidv4()});
}
addItem = () => {
let {inputValue, todos, id} = this.state
this.setState({todos: [...todos, {inputValue, id}]})
console.log('Assigned id to new item',this.state)
}
deleteItem = (todoID) => {
const todos = this.state.todos.filter((item => item.id !== todoID))
this.setState({todos})
console.log('------todoId',todoID)
}
editItem =(todoId) => {
}
render() {
console.log('-------render');
return (
<div className={"App"}>
<div className="App-header">
<h2>Welcome to To-Do List App</h2>
</div>
<input onChange={this.handleInputValue} name={''} type='text'/>
<button onClick={() => this.addItem()} className={'btn btn-primary'}>Add</button>
<ul>
{this.state.todos.map((item) => <li key={uuidv4()}>
<input type={'checkbox'}/>
<label>{item.inputValue}</label>
<input type={'text'} className={'hidden'}/>
<button onClick={() => this.deleteItem(item.id)} className={'btn btn-primary'}>Delete</button>
<button className={'btn btn-primary'}>Edit</button>
</li>)}
</ul>
</div>
)
}
}
export default App;
您正在寻找的是条件渲染。
基本上,您只在条件为真时渲染组件。 查看 React 文档,特别是关于内联 && 运算符的部分。
一个简单的例子:
使用&&
运算符仅在条件为真时渲染某些内容:
const Component = () => {
const [showMessage, setShowMessage] = useState(false);
return (
<div>
<button onClick={() => setShowMessage((p) => !p)}>Toggle message</button>
// the message div will only be rendered when showMessage is true
{showMessage && <div>This is a message!</div>}
</div>
);
};
使用三元运算符condition? a: b
condition? a: b
渲染一件事或另一件事:
const Component = () => {
const [showFirstMessage, setShowFirstMessage] = useState(false);
return (
<div>
<button onClick={() => setShowFirstMessage((p) => !p)}>
Toggle message
</button>
// If showFirstMessage is true, the first message will be rendered, else the second message will be rendered
{showFirstMessage ? (
<div>I'm the first message!</div>
) : (
<div>Hi, I'm the second message</div>
)}
</div>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.