【问题标题】:show/hide button in React JsReact Js 中的显示/隐藏按钮
【发布时间】:2021-03-24 07:24:06
【问题描述】:

有一个编辑按钮。那个编辑按钮,如果这些项目是在不到 6 小时内创建的,我想显示该按钮。该按钮的显示时间不应超过 6 小时。我使用moment js来计算时间。时间计算工作完美。但按钮可见性,不起作用。

当前时间状态

timenow:moment().format('H')

这是我的条件

{(moment(post.createdAt).add(6,'hour').format('H')< this.state.timenow)||( 
              <Button
                variant="outline-info"
                className="cardbutton"
                size="sm"
                onClick={this.editPost.bind(this, post._id, post.message)}
              >
                Edit
              </Button>)}

完整组件

import React, { Component } from "react";

import { Card, Button, Badge, Modal } from "react-bootstrap";
import pic2 from "./pic2.jpg";
import "./Forum.css";
import { BiMessageRounded } from "react-icons/bi";
import axios from "axios";
import moment from "moment";
import { RiDeleteBin6Line } from "react-icons/ri";
import { Link } from "react-router-dom";
//import  '../NotificationBar/SideNotification.css';

class Forum extends Component {
  constructor(props) {
    super(props);
    this.state = {
      message: "",
      posts: [],
      showModel: false,
      showConfirm: false,
      showDeleteConfirm: false,
      deletePost: "",
      editPost: { message: "", id: "" },
      visiblequestions: 10,
      visibletype: "",
      faculty:"",
      timenow:moment().format('H')
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
    this.loadmore = this.loadmore.bind(this);
    this.handletypechange = this.handletypechange.bind(this);
    this.handlefaculty = this.handlefaculty.bind(this);
    
  }

  handleChange(event) {
    this.setState({ message: event.target.value });
  }

  handleClick(event) {
    console.log(this.state.message);
    event.preventDefault();
    const message = { message: this.state.message ,faculty:this.state.faculty,privacytype:this.state.visibletype};

    axios.post("http://localhost:4000/Forum", message).then((res) => {
      console.log(res);
      console.log(res.data);
      this.handleCloseModal();
      this.getAllPosts();
    });

    this.setState({
      message: "",
    });
  }

  componentDidMount() {
    this.getAllPosts();
    this.timelimit();
   
  }

  getAllPosts = () => {
    axios
      .get("http://localhost:4000/Forum/home")
      .then((res) => this.setState({ posts: res.data.reverse() }));
  };

  deletePost = (id) => {
    axios
      .delete("http://localhost:4000/Forum/" + this.state.deletePost)
      .then((res) => {
        console.log(res);
        this.handleDeleteCloseModal();

        this.getAllPosts();
      });
  };

  editPost = (id, message) => {
    this.setState((currentState) => ({
      ...currentState,
      showModel: true,
      editPost: { message: message, id: id },
    }));
    console.log(this.state);
  };

  updatePost = () => {
    axios
      .patch("http://localhost:4000/Forum/" + this.state.editPost.id, {
        message: this.state.editPost.message,
      })
      .then((res) => {
        this.setState((currentState) => ({
          ...currentState,
          showModel: false,
        }));
        this.getAllPosts();
      });
  };

  onChangehandler = (e) => {
    e.persist();
    this.setState((currentState) => ({
      ...currentState,
      editPost: { ...currentState.editPost, message: e.target.value },
    }));
  };

  cancleEdit = () => {
    this.setState((currentState) => ({ ...currentState, showModel: false }));
    this.getAllPosts();
  };

  handleModal = () => {
    this.setState({ showConfirm: true });
  };

  handleCloseModal = () => {
    this.setState({ showConfirm: false });
  };

  handleDeleteModal = (id) => {
    this.setState(() => ({ showDeleteConfirm: true, deletePost: id }));
  };

  handleDeleteCloseModal = () => {
    this.setState({ showDeleteConfirm: false });
  };

  loadmore() {
    this.setState((old) => {
      return { visiblequestions: old.visiblequestions + 5 };
    });
  }

  handletypechange(event) {
    this.setState(
      { visibletype: event.target.value },
      console.log(this.state.visibletype)
    );
  }
  handlefaculty(event) {
    this.setState(
      { faculty: event.target.value },
      console.log(this.state.faculty)
    );
  }

  timelimit(id){
   if(this.state.timenow<2.30){
     console.log("yes");
   }else{
     console.log("no");
   }
    
    console.log(this.state.timenow);
    
  }
 
  

  render() {
    return (
      <div>
        <div class="sidenav">
          <h5 style={{ textAlign: "center", color: "white" }}>
            Notification Bar
          </h5>
        </div>
        <div className="divstyle">
          <Card className="forumstyle">
            <Card.Header as="h5">Post Question Here</Card.Header>
            <Card.Body>
              <Card.Title></Card.Title>
              <Card.Text>
                <textarea
                  style={{ width: "460px" }}
                  placeholder="Please write question here..."
                  value={this.state.message}
                  onChange={this.handleChange}
                />
              </Card.Text>
            </Card.Body>
            <div>
              <select
                className="form-select-sm select"
                aria-label="Default select example"
                onChange={this.handletypechange}
              >
                <option defaultValue hidden>Select Type</option>
                <option value="all">All</option>
                <option value="academic">Academic</option>
                <option value="student">Student</option>
              </select>
              {this.state.visibletype === "student" && (
                <select
                  className="form-select-sm select"
                  aria-label="Default select example"
                  onChange={this.handlefaculty}
                >
                  <option defaultValue hidden>Select Faculty</option>
                  <option value="All">All</option>
                  <option value="Engineering">Engineering</option>
                  <option value="Information Technology">
                    Information Technology
                  </option>
                  <option value="Architecture">Architecture</option>
                  <option value="Business">Business</option>
                </select>
              )}
            </div>
          </Card>
          <Button
            className="button"
            variant="primary"
            onClick={this.handleModal}
          >
            Post
          </Button>
        </div>

        <div style={{ backgroundColor: "rgba(192,192,192,0.3)" }}>
          {this.state.posts
            .slice(0, this.state.visiblequestions)
            .map((post) => (
              <Card
                key={post._id}
                style={{
                  width: "500px",
                  marginLeft: "30%",
                  marginBottom: "30px",
                  marginTop: "20px",
                  border: "1px solid grey",
                }}
              >
                <Card.Header>
                  <img
                    src={pic2}
                    style={{ width: "20px" }}
                    className="rounded mr-2"
                    alt=""
                  />
                  Anushka Praveen
                  <small style={{ float: "right" }}>
                    {moment(post.createdAt).fromNow()}
                  </small>
                </Card.Header>

                <Card.Body>
                  <Card.Text>{post.message}</Card.Text>
                  <Link
                    to={{
                      pathname: "Forum/ForumReply",
                      query: { id: post._id },
                    }}
                  >
                    <Button
                      variant="outline-info"
                      className="cardbutton"
                      size="sm"
                    >
                      <BiMessageRounded style={{ marginRight: "2px" }} />
                      Reply
                      <Badge className="badgestyle" variant="info">
                        {post.reply.length}
                      </Badge>
                    </Button>
                  </Link>
                  
                 {moment(post.createdAt).add(6,'hour').format('H')>this.state.timenow &&( 
                  <Button
                  
                    variant="outline-info"
                    className="cardbutton"
                    size="sm"
                    onClick={this.editPost.bind(this, post._id, post.message)}
                  >
                    Edit
                  </Button>)}
                  <Button
                    variant="outline-danger"
                    className="carddeletebutton"
                    size="sm"
                    onClick={() =>
                      this.handleDeleteModal(post._id)
                    } /* {this.deletePost.bind(this, post._id)} */
                  >
                    <RiDeleteBin6Line />
                  </Button>
                </Card.Body>
              </Card>
            ))}
          <div class="col-md-12 p-3 text-center">
            {this.state.visiblequestions < this.state.posts.length && (
              <button
                type="button"
                class="btn btn-outline-info"
                onClick={this.loadmore}
              >
                Read more
              </button>
            )}
          </div>
        </div>
        <Modal show={this.state.showModel}>
         <Modal.Header>
            <Modal.Title>Edit Question</Modal.Title>
          </Modal.Header>

          <Modal.Body>
            <textarea
              style={{ width: "29rem" }}
              value={this.state.editPost.message}
              onChange={this.onChangehandler}
            >
              {this.state.editPost.message}
            </textarea>
          </Modal.Body>

          <Modal.Footer>
            <Button variant="secondary" onClick={this.cancleEdit}>
              Close
            </Button>
            <Button variant="primary" onClick={this.updatePost}>
              Save
            </Button>
          </Modal.Footer>
        </Modal>

        <Modal show={this.state.showConfirm}>
          <Modal.Header>
            <Modal.Title>Post Question</Modal.Title>
          </Modal.Header>
          <Modal.Body>Do you want post this Question?</Modal.Body>
          <Modal.Footer>
            <Button variant="secondary" onClick={this.handleCloseModal}>
              Close
            </Button>

            <Button variant="danger" onClick={this.handleClick}>
              Post Question
            </Button>
          </Modal.Footer>
        </Modal>

        <Modal show={this.state.showDeleteConfirm}>
          <Modal.Header>
            <Modal.Title>Delete Question</Modal.Title>
          </Modal.Header>
          <Modal.Body>Do you want Delete this Question?</Modal.Body>
          <Modal.Footer>
            <Button variant="secondary" onClick={this.handleDeleteCloseModal}>
              Close
            </Button>

            <Button variant="danger" onClick={this.deletePost}>
              Delete Question
            </Button>
          </Modal.Footer>
        </Modal>
        
      </div>
    );
  }
}

export default Forum;

【问题讨论】:

    标签: javascript reactjs momentjs


    【解决方案1】:

    也许尝试以这种方式有条件地渲染它会有所帮助。

    {(!(moment(post.createdAt).add(6,'hour').format('H')< this.state.timenow))? 
                  <Button
                    variant="outline-info"
                    className="cardbutton"
                    size="sm"
                    onClick={this.editPost.bind(this, post._id, post.message)}
                  >
                    Edit
                  </Button>:<>"empty"</>}

    【讨论】:

    • 控制台中是否弹出任何特定时刻的错误?
    • 为了澄清,我们究竟从哪里得到 post.createdAt 的值?另外,您能否根据两个值的差值大于 6 来确定条件?
    • (moment(post.createdAt).add(6,'hours')>moment()) 此代码工作正常
    【解决方案2】:

    您的条件渲染看起来不错。 || 运算符评估左侧,如果为假,则移动到右侧。而&amp;&amp; 运算符评估左侧,如果为真则继续

    如果按钮少于 6 小时,您希望显示该按钮。因此,您希望 (moment(post.createdAt).add(6,'hour').format('H') &lt; this.state.timenow) 评估为 true 并仅在语句为 true 时才呈现 Button

    {(moment(post.createdAt).add(6,'hour').format('H') < this.state.timenow) && ( 
                      <Button
                        variant="outline-info"
                        className="cardbutton"
                        size="sm"
                        onClick={this.editPost.bind(this, post._id, post.message)}
                      >
                        Edit
                      </Button>)}
    

    【讨论】:

    • moment(post.createdAt).add(6,'hour').format('H') 这就是问题所在,很可能
    • 你对这个问题有什么想法吗?
    • 你能console.log((moment(post.createdAt).add(6,'hour').format('H'))console.log(this.state.timenow)得到什么吗?
    • 我检查了控制台日志中显示的值。这些值是正确的。
    • 那么其他地方有问题。您可以编辑问题并粘贴整个组件吗?
    猜你喜欢
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 2020-05-09
    • 2022-01-26
    • 1970-01-01
    • 2020-08-31
    • 2021-11-27
    • 1970-01-01
    相关资源
    最近更新 更多