gpt4 book ai didi

javascript - 使用react-spring而不使用jsx

转载 作者:行者123 更新时间:2023-12-02 23:54:21 26 4
gpt4 key购买 nike

我想使用react-spring 来做一些基本的动画。我能找到的所有示例都是基于 JSX,显然大多数人在开发 React 时都在使用 JSX。然而在我正在实现的项目中,JSX已被关闭,而且import也是非法的,只有require可用。这是一些保持代码约定的 es-lint 设置。

我尝试过以下操作:

const createReactClass = require('create-react-class');
const React = require('react');
const Spring = require('react-spring');

const h = React.createElement;

const SectionCollapse = createReactClass({
render: function () {
return (
h(Spring, {
from: { opacity: 0 },
to: { opacity: 1 }
},
(sp) => {
return h('div', {}, 'should render');
}));
}
});

但我收到错误:

react.development.js:188 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of SectionCollapse.

这可能是我所缺少的一些简单的道理,

最佳答案

查看 https://www.react-spring.io/docs/hooks/basics 的第一个示例在我看来,您正在尝试从 JSX 到非 JSX。

所以原来的例子是:

import { useSpring, animated } from 'react-spring'

function App() {
const props = useSpring({ opacity: 1, from: { opacity: 0 } })
return <animated.div style={props}>I will fade in</animated.div>
}

转换您的导入基本上是正确的。

var Spring = require("react-spring");

但是我认为您的 h() 函数属性缺少一些信息 - 这就是我在使用 https://babeljs.io/repl 检查后转换 JSX 的方式。 .

  return h(Spring.animated.div, {
style: {
opacity: 1,
from: {
opacity: 0
}
}
}, "I will fade in");

回到你的例子,这应该可以解决问题(未经测试):

const createReactClass = require('create-react-class');
const React = require('react');
const Spring = require('react-spring');

const h = React.createElement;

const SectionCollapse = createReactClass({
render: function () {
return (h(Spring.animated.div, { style: {
from: { opacity: 0 },
to: { opacity: 1 }
}
},
h('div', {}, 'should render')));
}
});

关于javascript - 使用react-spring而不使用jsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55471513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com