javascript - 如何从屏幕中的组件获取 Prop ?

标签 javascript reactjs react-native

大家好,我已经创建了一个星级评定组件,现在我已将其添加到我的屏幕中。我现在的问题是如何获取屏幕内的组件返回值,以便在提交时将其发送到服务器。

这是我的组件

export default class StarsRating extends Component {
    constructor(props) {
        super(props)
        this.state = {
            rating: this.props.rating || null,
            temp_rating: null
        }
    }

    rate(rating) {
        this.setState({
            rating: rating,
            temp_rating: rating
        });
    }

    render() {
        // This array will contain our star tags. We will include this
        // array between the view tag.
        let stars = [];
        // Loop 5 times
        for (var i = 1; i <= 5; i++) {
            // Set the icon to filled stars
            let icon = "star-outline";
            // If ratings is lower, set the icon to unfilled stars
            if (this.state.rating >= i && this.state.rating != null) {
                icon = "star";
            }
            // Push the Icon tag in the stars array
            stars.push((
                <TouchableOpacity key={i} onPress={this.rate.bind(this, i)}>
                    <Icon
                        name={icon}
                        size={40}
                        color={colors.yellow}
                    />
                </TouchableOpacity >
            ));
        }

        return (
            <View style={styles.wrapper}>
                {stars}
            </View>
        );
    }
}

在我的屏幕上我可以像这样访问它 <StarsRating />

最佳答案

最好的选择是将 onChanged 函数作为 Prop 从屏幕(渲染它的地方)传递给您的组件。

<StarsRating onChanged={(rating) => {
    // yourFunctionWithApiCall(rating)
    // axios.post() directly here 
}} />

StarsRating组件中,您只需在rate方法中添加对此函数的调用即可。

rate(rating) {
    this.setState({
        rating: rating,
        temp_rating: rating
    });

    // when You think that value should be saved to API call function passed with props
   this.props.onChanged(rating);
}

一般来说 - 将此 api 通信函数作为 props 传递给您的组件。因此,当评级更改后的行为可能不同时,您将可以在另一个项目中重用它。

关于javascript - 如何从屏幕中的组件获取 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53979667/

相关文章:

javascript - 简单的方法而不是在 JavaScript 中重复调用函数

javascript - 在 JavaScript 中定期更改图像

javascript - 在 firebase 数据库中搜索具有特定键值的元素对象

javascript - react 类 : setState does nothing (and no errors reported)

javascript - ToolbarAndroid 中的下拉图标 + 捕获标题点击事件 + 搜索输入(原生 react )

javascript - 如何使用普通 JavaScript 和/或状态生成 future 日期?

javascript - 如何在不删除网站其余部分的情况下跳转网页?

javascript - ./node_modules/react-dom/cjs/react-dom.development.js :25058 中的函数 createFiberFromTypeAndProps 出错

javascript - 导入的 React 组件具有不需要的宽度 : 0 div at root and is stopping the component fill the parents CSS grid area

android - 使用 React Native 创建原生 SDK