【问题标题】:function as JSX - React Native作为 JSX 的功能 - React Native
【发布时间】:2021-05-27 00:17:12
【问题描述】:

我希望这个函数显示在 JSX 代码中

function getValue() {
const QuestionChild = ['zara','whats up1','have u ever been in uk1']
const randomItem = QuestionChild[Math.floor(Math.random() * QuestionChild.length)];
console.log(randomItem)
return randomItem
}

控制台日志显示此结果但无法在代码中显示

这里是 JSX:

                <TouchableOpacity>
                <View style={styles.btnBack}><Text style={styles.smallwowo}>Back</Text></View> 
            </TouchableOpacity>

            <View style={styles.box}>
            <Text>{getValue}</Text>
            <TouchableOpacity onPress={()=> {getValue} }>
             <View style={styles.btn}><Text style={styles.wowo}>Next</Text></View>
             </TouchableOpacity>

当点击下一步按钮时,它应该从问题数组中返回随机选择的字符串

【问题讨论】:

    标签: javascript arrays reactjs react-native


    【解决方案1】:

    您应该存储一些状态——无论是通过useState 还是通过有状态组件——并让getValue 函数更改该状态。

    那么你会做&lt;TouchableOpacity onPress={getValue}&gt;,而不是onPress={()=&gt; {getValue} }

    【讨论】:

    • 我已编辑,但出现错误提示我错误地调用了钩子
    • const [result,setResult] = useState('') const QuestionChild = ['zara','whats up1','你去过uk1吗'] const randomItem = QuestionChild[Math.floor (Math.random() * QuestionChild.length)]; function getValue() { const QuestionChild = ['zara','whats up1','你去过 uk1'] const randomItem = QuestionChild[Math.floor(Math.random() * QuestionChild.length)]; console.log(randomItem) setResult(randomItem) }`
    • @NERD 这是我在浏览器中的操作方式,一般的想法在 react native 中应该是一样的:codesandbox.io/s/react-hooks-usestate-forked-rto65?file=/src/…
    【解决方案2】:

    EDIT 使用钩子并将getValue() 与状态相关的关注点分开:

    让您的 getValue 函数与您原来的函数相同。

    组件顶部的某处:

    const [randomValue, setRandomValue] = useState(getValue());
    

    然后在下面的某个地方创建一个新的onPress 处理程序:

    const onGetNewValue = () => setRandomValue(getValue());
    
    

    然后在您的onPress 声明中:

    <TouchableOpacity onPress={onGetNewValue}>
    

    您实际显示该值的位置是

    <Text>{randomValue}</Text>
    

    旧答案:

    首先,要实际显示值,需要实际调用函数,所以使用

    &lt;Text&gt;{getValue()}&lt;/Text&gt;

    接下来,要让按钮按下更改值,您需要将值存储在一个状态中,这将触发重新渲染。有不同的方法可以做到这一点,但我建议在你的构造函数中,创建

    this.state = { randomValue: getValue() }

    然后在getValue

    ...
    const randomItem = QuestionChild[Math.floor(Math.random() * QuestionChild.length)];
    this.setState({ randomValue: randomItem });
    

    然后改为使用

    <Text>{this.state.randomValue}</Text>
    

    现在,每次单击按钮时,都会为 state 存储一个新值,并且您的组件将使用新的 state 值重新渲染。

    【讨论】:

    • 非常感谢,但你能用 useState 告诉它,因为我正在传递导航,所以它会更舒服
    猜你喜欢
    • 2022-06-22
    • 2019-10-09
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 2018-05-28
    相关资源
    最近更新 更多