【问题标题】:reactstrap tooltip dynamic idreactstrap 工具提示动态 id
【发布时间】:2018-07-02 10:55:54
【问题描述】:

我正在开发一个 react 应用程序并使用 reactstrap。

我正在使用 reactstrap 的 Tooltip 组件,它需要一个目标属性,即目标元素 id 的值。这个 id 是动态生成的,似乎 reactstrap 工具提示不喜欢它。

组件看起来像:

MovieCard.jsx

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Col, Card, CardImg, CardBody, CardTitle, CardSubtitle, CardText, Button, Tooltip } from 'reactstrap';
import { LimitedTextTitle } from '../custom-styled/CustomStyledComponents';

class MovieCard extends Component {  

  constructor (props) {
    super(props);
    this.state = {
      open: false
    };
    this.toggle = this.toggle.bind(this);
  }

  toggle () {
    this.setState({
      open: !this.state.open
    })
  }

  render () {
    const { imdbID, Title, Year, Rated, Plot, Country, Poster } = this.props.movie;

    return (
  <Col md="4">
    <Card>
      <CardImg
        top
        width="100%"
        src={Poster}
        alt="blah"
      />
    </Card>
    <CardBody>
      <CardTitle>
        <LimitedTextTitle id={imdbID}>
          {`${Title} - (${Year})`}
        </LimitedTextTitle>
        <Tooltip placement='top' target={imdbID} isOpen={this.state.open} toggle={this.toggle}>
          {Title}
        </Tooltip>
      </CardTitle>
      <CardSubtitle>{`Rated: ${Rated} Country: ${Country}`}</CardSubtitle>
      <CardText>{Plot}</CardText>
      <Button>Read More</Button>
    </CardBody>
  </Col>
);
  }
}

MovieCard.propTypes = {
  movie: PropTypes.object.isRequired // eslint-disable-line
};

export default MovieCard;

有什么建议吗?

反应版本 16.2.0

reactstrap 5.0.0-alpha.4

【问题讨论】:

  • 看起来不错。您在控制台中有任何错误/警告吗?还是工具提示仅出现在某些项目上?还是 imdb id 为空/空?
  • imdbID 不为空,控制台中的错误提示,目标未定义,但如果我删除工具提示并运行上面的代码,它会生成填充的 id 属性。
  • 哇.. 你能给我看看LimitedTextTitle 的渲染吗?
  • github.com/priyankthakkar/open-movie-web.git 这里是源代码。参考分支“登陆页面”
  • 您尚未在任何地方呈现您的 id。您已将它作为道具传递给styled-component,但它没有呈现在页面上。将其包装在 div/span 中并将id 传递给它。

标签: reactjs bootstrap-4 reactstrap


【解决方案1】:

正在处理类似的问题。

添加代码作为答案,因为我无法在上面添加评论...

希望它能帮助您或遇到此问题的任何其他人。

说明: 对动态生成的元素使用 reactstrap 工具提示。

import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Button, Tooltip } from 'reactstrap';

class App extends React.Component {
  state = {};

  toggle = targetName => {
    if (!this.state[targetName]) {
      this.setState({
        ...this.state,
        [targetName]: {
          tooltipOpen: true
        }
      });
    } else {
      this.setState({
        ...this.state,
        [targetName]: {
          tooltipOpen: !this.state[targetName].tooltipOpen
        }
      });
    }
  };

  isToolTipOpen = targetName => {
    return this.state[targetName] ? this.state[targetName].tooltipOpen : false;
  };

  render() {
    return (
      <div>
        {[1, 2, 3, 4, 5, 6].map((x, i) => (
          <div key={`div-${i}`}>
            <Button color="link" id={`btn-${i}`}>
              {x}
            </Button>
            <Tooltip
              placement="right"
              isOpen={this.isToolTipOpen(`btn-${i}`)}
              target={`btn-${i}`}
              toggle={() => this.toggle(`btn-${i}`)}>
              Hello world!
            </Tooltip>
          </div>
        ))}
      </div>
    );
  }
}

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

反应:16.9.0

reactstrap:8.0.1

https://codesandbox.io/embed/angry-taussig-fup7i?fontsize=14

【讨论】:

    【解决方案2】:

    尤里卡我明白了!!!基于 Meir Keller 的回答,无需检查工具提示的状态是否已经存在。如果不存在,则默认为false...

    只要定义了状态,即使它是空状态,也可以。

    这是使用 reactstrap 的 Popover,但它是相同的概念。

    import React, { Component, Fragment } from 'react';
    import './App.css';
    import 'bootstrap/dist/css/bootstrap.min.css'
    import { Container, Row, Col, Input, Button, Popover } from 'reactstrap';
    
    class App extends Component {
      state = {};
    
      toggle = (target) => {
        // console.log(typeof target) // make sure this is a string
        this.setState({
          ...state,
          [target]: !this.state[target]
        });
      };
    
      render() {
        return (
          <Container>
          {["Hello", "Greetings"].map((name) => (
    
          <Row>
          <Fragment>
              <Button id={name} type="button">{name}</Button>
              <Popover placement="right" 
              isOpen={this.state[`${name}`]} 
              target={name}
              toggle={() => this.toggle(`${name}`)}>
              <PopoverBody>
                You've got mail. Did you know?
                </PopoverBody>
                </Popover>
                </Fragment>
          </Row>
          ))}
          </Container>
        );
      }
    }
    
    export default App;
    

    【讨论】:

      【解决方案3】:

      在模块化或组件目录中创建一个新组件并粘贴此代码

      import React, { useState } from "react";
      import { Tooltip } from "reactstrap";
      
      const TooltipItem = props => {
          const { position='top', id } = props;
          const [tooltipOpen, setTooltipOpen] = useState(false);
      
          const toggle = () => setTooltipOpen(!tooltipOpen);
      
          return (
              <span>
            <span id={"tooltip-" + id}>
                  {props.children}
            </span>
            <Tooltip
                placement={position}
                isOpen={tooltipOpen}
                target={"tooltip-" + id}
                toggle={toggle}
            >
                {props.title}
            </Tooltip>
          </span>
          );
      };
      
      
      export default TooltipItem;

      现在导入并使用此工具提示组件

      import TooltipItem from "../Tooltip";
      
       <TooltipItem id={'edit' + data.id} title={'Edit Store'}>
          <i className="fas fa-edit pointer" onClick={() => this.onEditClick(data)}/>
        </TooltipItem>
      

      【讨论】:

        【解决方案4】:

        我想为它添加一个答案,因为已经有很多人提到了很多解决问题的方法。 但是reactStrap 工作得非常好,大多数初学者在创建id 时都会犯错误,他们使用特殊字符,例如:

        - _ / @ 甚至可以是space

        只需保留 id 一个非常简单的字符和数字组合,reactstrap 就可以正常工作

        【讨论】:

          【解决方案5】:

          新组件UncontrolledTooltip 将解决问题。只需使用

           <UncontrolledTooltip
             placement="right"
             target={`btn-${i}`}
           >
             {props.title}
           </UncontrolledTooltip>
          

          【讨论】:

            【解决方案6】:

            我尝试了很多解决方案,但当目标元素不在 Dom 中时,Reactstrap Tooltip 仍然会崩溃。

            我结合了人们发布的其他几个解决方案,这是它对我有用的唯一方法。条件渲染 FTW。

            const ElementWithTooltip = ({
                dynamicIdentifier, // string, number, w/e
            }): ReactElement => {
                // Target element state.
                const [isTargetReady, setIsTargetReady] = useState(false);
                
                // Target element ref.
                const tooltipRef = useRef(null);
             
                // Hook to recognize that the target is ready.
                useEffect(() => {
                    const targetElement = tooltipRef.current;
                    if (targetElement) {
                        setIsTargetReady(true);
                    }
                  }, [tooltipRef.current]);
            
                // TSX.
                return (
                    <>
                        <span ref={tooltipRef}>This is the target element</span>
                        {isTargetReady && <UncontrolledTooltip autohide={false} target={tooltipRef}>
                            Tooltippy text stuff
                        </UncontrolledTooltip>}
                    </>
                );
            

            【讨论】:

              猜你喜欢
              • 2020-09-11
              • 2020-12-27
              • 2019-04-13
              • 1970-01-01
              • 2020-12-10
              • 1970-01-01
              • 2021-06-08
              • 2019-06-14
              • 2014-07-01
              相关资源
              最近更新 更多