代码之家  ›  专栏  ›  技术社区  ›  Darren

来自父级组件的jsx作为字符串

  •  0
  • Darren  · 技术社区  · 7 年前

    我有一个组件 5 并返回jsx返回中的当前计数。

    注意:通常我会使用一个函数并使用返回值,但是这很麻烦,因为组件使用react钩子并在调用函数时导致错误。

    我的倒计时组件是

    import React, { useEffect, useState } from 'react';
    
    const countdownSeconds = 5;
    const Countdown = () => {
      const [timing, setTiming] = useState(true);
      const [second, setSecond] = useState(countdownSeconds);
      useEffect(() => {
        let interval: number;
        if (timing) {
          interval = setInterval(() => {
            setSecond(preSecond => {
              if (preSecond <= 1) {
                setTiming(false);
                clearInterval(interval);
                return countdownSeconds;
              } else {
                return preSecond - 1;
              }
            });
          }, 1000);
        }
        return () => clearInterval(interval);
      }, [timing]);
    
      return <>${timing ? second : 0}</>;
    };
    
    export default Countdown;
    

    我想用 <Countdown /> 在一个 string 在里面 props 另一个组件的。

    <Typography
      text={
        `countdown is` + <Countdown /> + `seconds`
      }
    />
    

    这显然又回来了 [object Object] .

    我怎样才能得到 <>${timing ? second : 0}</> 作为字符串传递给 <Typography /> ?

    我不想用 Context 如果可能的话。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Clue Mediator    7 年前

    你必须这样更新你的代码。

    <Typography
      text={
        <>
          <span>countdown is</span> <Countdown /> <span>seconds</span>
        </>
      }
    />
    

    希望这对你有用!