[英]How to export variable from react component?
我正在使用 Mantine 作為搜索欄,我需要獲取文本區域的字數。 這是使用 Nodejs 和 React。 我需要能夠導出此值以在不同的文件中使用。
import React, { useState } from 'react';
import { TextInput, createStyles } from '@mantine/core';
var count = document.getElementById('count');
const useStyles = createStyles((theme, { floating }: { floating: boolean }) => ({
root: {
position: 'relative',
},
label: {
position: 'absolute',
zIndex: 2,
top: 7,
left: theme.spacing.sm,
pointerEvents: 'none',
color: floating
? theme.colorScheme === 'dark'
? theme.white
: theme.black
: theme.colorScheme === 'dark'
? theme.colors.dark[3]
: theme.colors.gray[5],
transition: 'transform 150ms ease, color 150ms ease, font-size 150ms ease',
transform: floating ? `translate(-${theme.spacing.sm}px, -28px)` : 'none',
fontSize: floating ? theme.fontSizes.xs : theme.fontSizes.sm,
fontWeight: floating ? 500 : 400,
},
required: {
transition: 'opacity 150ms ease',
opacity: floating ? 1 : 0,
},
input: {
'&::placeholder': {
transition: 'color 150ms ease',
color: !floating ? 'transparent' : undefined,
},
},
}
)
);
export function FloatingLabelInput() {
const [focused, setFocused] = useState(false);
const [value, setValue] = useState('');
const { classes } = useStyles({ floating: value.trim().length !== 0 || focused });
const uniqueid = "input";
return(
<TextInput
id={ uniqueid }
placeholder="Add anything you want to the book of the internet."
required
classNames={classes}
value={value}
onChange={(event) => setValue(event.currentTarget.value)}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
mt="md"
onKeyUp={(e) => {
var text = value.split(' ');
var wordcount = 0;
for (var i = 0; i < text.length; i++) {
if (text[i] !== ' ') {
wordcount++;
}
}
count.innerText = wordcount;
}
}
autoComplete="nope"
/>
);
}
如您所見,它正確地將其輸出到 html,但在 function 內部返回根本不起作用。
我嘗試導出它,我嘗試將它返回到 function 但它沒有看到它。 我嘗試導出和使用模塊導出,但這也不起作用。 任何幫助,將不勝感激。
在下面的代碼片段中,我的根組件(稱為 App)負責保留應用程序 state,但它可以將 state 的任何部分提供給它的任何子組件。 它還可以為其子項提供 state 修飾符( setX
函數),這就是我在這里演示的內容:
function Input ({ setWordCount }) { function updateWordCount (event) { setWordCount(event.target.value.split(' ').length) } return <input type="text" onKeyUp={updateWordCount} /> } function SomeOtherComponent ({ count }) { return ( <span>: {count} words</span> ) } function App () { const [wordCount, setWordCount] = React.useState(0) return ( <p> <Input setWordCount={setWordCount} /> <SomeOtherComponent count={wordCount} /> </p> ) } ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.5/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.5/umd/react-dom.production.min.js"></script> <div id="app" />
可以看到, Input
組件可以調用其parent提供的setWordCount
function來改變一塊state,然后parent(App)可以將這塊state給任意數量的children。 每個組件也可以存在於一個單獨的文件中,這仍然有效……
我不確定我是否正確理解了您的問題,但希望這可以為您提供可以在您自己的代碼中重用的想法?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.