简体   繁体   中英

imported functions don't work under render()

I am attempting to move a bunch of reusable functions into a convenient place, but I'm having issues with using them in other files. I am using a static React.js frontend without Node.

miscFunctions.js

export const capitalize = (string) => {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

module.exports = {
  capitalize,
  other functions...
}

Test.js

import React, { Component } from 'react';
import capitalize from './miscFunctions';

class Test extends Component {
  constructor(props) {
    super(props);
    this.capitalize = capitalize.bind(this);
  }
  render() {
    return (
      <div>
        {this.capitalize("foo")}
      </div>
    );
  }
}

export default Test;

capitalize() works just fine so long as it's used in a class function, but once I try to use it within render(), it doesn't exist. I get the message "TypeError: Cannot read property 'bind' of undefined"

You don't need to put the capitalize function on the component at all. You can remove it from the constructor and just use it as is.

capitalize is a named export, so you need to import it with that in mind.

// miscFunctions.js
export const capitalize = (string) => {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

// Test.js
import React, { Component } from 'react';
import { capitalize } from './miscFunctions';

class Test extends Component {
  render() {
    return (
      <div>
        {capitalize("foo")}
      </div>
    );
  }
}

export default Test;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM